6

Lesson 6: Lists and Data Structures

Working with collections of data

Learning Objectives

By the end of this lesson, students will:

  • Create and manipulate lists effectively
  • Use list methods for common operations
  • Understand tuples and dictionaries
  • Apply list comprehensions for efficient coding

Skills Developed:

  • Data organization and management
  • Collection processing techniques
  • Algorithm thinking with data sets

Lesson Content

1 Lists Basics (20 minutes)

What are Lists?

  • • Ordered collections of items
  • • Can store different data types
  • • Mutable (can be changed after creation)
  • • Use square brackets [ ] and commas
# Creating lists
robot_sensors = ["camera", "ultrasonic", "gyroscope"]
battery_levels = [100, 85, 92, 78]
mixed_data = ["Robot1", 25.5, True, 42]
empty_list = []
# Accessing list items (indexing)
print(robot_sensors[0]) # "camera"
print(robot_sensors[1]) # "ultrasonic"
print(robot_sensors[-1]) # "gyroscope" (last item)
# List slicing
first_two = robot_sensors[0:2] # ["camera", "ultrasonic"]
last_two = robot_sensors[1:] # ["ultrasonic", "gyroscope"]
print(f"Sensors: {first_two}")

Instructor Notes:

Emphasize that lists start at index 0, not 1. Use robot examples - list of sensors, waypoints, or commands. Show negative indexing for accessing from the end.

2 List Methods and Operations (20 minutes)

Common List Methods:

  • append() - add to end
  • insert() - add at position
  • remove() - remove by value
  • pop() - remove by index
  • sort() - arrange in order
  • reverse() - flip order
  • len() - get length
  • count() - count occurrences
# Robot command queue
commands = ["move_forward", "turn_left", "scan"]
# Adding commands
commands.append("move_backward")
commands.insert(1, "check_battery")
print(f"Commands: {commands}")
# Removing commands
commands.remove("scan")
last_command = commands.pop() # Remove and return last
print(f"Removed: {last_command}")
# List operations
distances = [15, 8, 23, 12, 30]
distances.sort()
print(f"Sorted distances: {distances}")
print(f"Number of readings: {len(distances)}")
print(f"Shortest distance: {min(distances)}")
print(f"Average: {sum(distances) / len(distances)}")

3 Tuples and Dictionaries (15 minutes)

Data Structure Comparison:

Tuples:
  • • Immutable (cannot change)
  • • Use parentheses ( )
  • • Good for coordinates, RGB values
  • • Faster than lists
Dictionaries:
  • • Key-value pairs
  • • Use curly braces
  • • Access by key, not index
  • • Perfect for robot settings
# Tuples - robot coordinates
start_position = (0, 0)
current_position = (15, 23)
rgb_color = (255, 128, 0) # Orange
x, y = current_position # Unpacking
print(f"Robot at ({x}, {y})"))
# Dictionaries - robot configuration
robot_config =
"name": "AutoBot",
"max_speed": 50,
"battery_capacity": 5000,
"sensors": ["camera", "lidar"]
# Accessing dictionary values
print(f"Robot name: {robot_config["name"]}")
robot_config["current_battery"] = 4200
print(f"Battery: {robot_config["current_battery"]}mAh")

4 List Comprehensions (10 minutes)

Efficient List Creation:

  • • Create lists in one line of code
  • • Apply operations to each item
  • • Include conditional filtering
  • • More Pythonic and often faster
# Traditional way
squares = []
for i in range(1, 6):
squares.append(i ** 2)
print(squares) # [1, 4, 9, 16, 25]
# List comprehension way
squares = [i ** 2 for i in range(1, 6)]
print(squares) # Same result!
# With conditions
sensor_readings = [12, 25, 8, 30, 15, 45]
high_readings = [x for x in sensor_readings if x > 20]
print(f"High readings: {high_readings}")
# Processing robot data
temperatures = [20.5, 22.1, 19.8, 25.3]
fahrenheit = [c * 9/5 + 32 for c in temperatures]
print(f"Fahrenheit: {fahrenheit}")

Hands-On Activity (25 minutes)

Project: Robot Mission Planner

Students will create a program that manages robot missions using various data structures.

Requirements:

  • • Create lists for waypoints, tasks, and sensor readings
  • • Use a dictionary to store robot status information
  • • Implement functions to add, remove, and process mission data
  • • Use list comprehensions for data processing
  • • Include tuple coordinates for robot positions
  • • Create a mission summary report

🤖🗺️ How to Code This Project (Choose Your Platform):

📱 Pythonista 3:
  1. Open Pythonista 3
  2. Tap "+" → "Empty Script"
  3. Name it "mission_planner.py"
  4. Type the code below
  5. Tap ▶️ to run
  6. Test data operations
Tip: Use list comprehensions for efficiency
🤖 Pydroid 3:
  1. Open Pydroid 3
  2. Tap "+" → "Python file"
  3. Name it "mission_planner.py"
  4. Type the code below
  5. Tap ▶️ yellow play button
  6. Test data operations
Tip: Practice dictionary operations
💻 PC/Mac:
  1. Open IDLE or editor
  2. Create new file
  3. Save as "mission_planner.py"
  4. Type the code below
  5. Press F5 to run
  6. Test data operations
Tip: Experiment with list methods
# Robot Mission Planner
print("🤖 Robot Mission Planner v1.0")
# Mission data structures
waypoints = [(0, 0), (10, 5), (15, 15), (20, 10)]
tasks = ["scan_area", "collect_sample", "take_photo"]
sensor_readings = [25, 30, 28, 32, 27, 29]
robot_status =
"name": "Explorer-1",
"battery": 85,
"current_position": (0, 0),
"mission_complete": False
def add_waypoint(x, y):
waypoints.append((x, y))
print(f"Added waypoint: ({x}, {y})")
def process_sensor_data():
avg_temp = sum(sensor_readings) / len(sensor_readings)
high_temps = [t for t in sensor_readings if t > avg_temp]
return avg_temp, high_temps
def mission_summary():
print(f"\n📊 Mission Summary for {robot_status["name"]}")
print(f"Waypoints to visit: {len(waypoints)}")
print(f"Tasks remaining: {len(tasks)}")
print(f"Battery level: {robot_status["battery"]}%")
avg, high = process_sensor_data()
print(f"Average temperature: {avg:.1f}°C")
print(f"High readings: {high}")
# Run the mission planner
add_waypoint(25, 20)
tasks.append("return_to_base")
mission_summary()

Assessment & Homework

Quick Check (In Class):

  • • Can student create and manipulate lists?
  • • Do they understand list indexing and slicing?
  • • Are they using appropriate data structures?
  • • Can they write basic list comprehensions?

Homework Assignment:

Inventory Management System

Create a program that manages a robot parts inventory using lists, dictionaries, and tuples. Include functions to add/remove items, search inventory, generate reports, and process bulk operations using list comprehensions.