Week 6: Lists in Python

CMPSC 100 Computational Expression

Janyl Jumadinova

Data Structures

Organizing collections of data

What are Data Structures?

  • Data structures organize collections of related data
  • Much better than using many individual variables
  • Lists are our first data structure!

Problem:

student1 = "Maya"
student2 = "Jamal" 
student3 = "Sofia"
# What if we have 100 students?

Solution:

students = ["Maya", "Jamal", "Sofia"]

Lists in Python

Collections of items in order

Creating Lists

# Empty list
my_list = []

# List with items
colors = ["red", "blue", "green"]
numbers = [10, 20, 30]

# Mixed types allowed
student = ["Kenji", 20, True]

Accessing List Items

colors = ["red", "blue", "green"]
#         [0]    [1]     [2]

print(colors[0])   # "red" (first)
print(colors[2])   # "green" (third)
print(colors[-1])  # "green" (last)
print(len(colors)) # 3 (total count)

Output:

red
green
green
3
  • Indexing starts at 0
  • Negative indices count from the end
  • len() gives total number of items

For Loops with Lists

Loop through items:

colors = ["red", "blue", "green"]
for color in colors:
    print(color)

Output:

red
blue
green

Loop with indices (when you need position):

scores = [85, 92, 78]
for index in range(len(scores)):
    print(f"Student {index+1}: {scores[index]} points")

Output:

Student 1: 85 points
Student 2: 92 points
Student 3: 78 points

Example: Finding the Maximum

scores = [85, 92, 78, 95, 88]

# Find highest score
highest = scores[0]
for score in scores:
    if score > highest:
        highest = score
        
print(f"Highest score: {highest}")
print(f"Total students: {len(scores)}")

Output:

Highest score: 95
Total students: 5

Key Points

  • Create: my_list = [item1, item2, item3]
  • Access: my_list[0] (first), my_list[-1] (last)
  • Length: len(my_list)
  • Loop by item: for item in my_list:
  • Loop by index: for index in range(len(my_list)):

Remember: Indexing starts at 0!

List Slicing

Getting parts of a list

led_names = ["Red", "Yellow", "Green", "Blue", "White"]
flash_counts = [2, 3, 4, 5, 6, 7]

# Get first 3 items
first_three = led_names[:3]
print(first_three)  # ["Red", "Yellow", "Green"]

# Get last 2 items  
last_two = led_names[-2:]
print(last_two)     # ["Blue", "White"]

# Reverse the entire list
reversed_list = led_names[::-1]
print(reversed_list) # ["White", "Blue", "Green", "Yellow", "Red"]

# Use in patterns
for count in flash_counts[:3]:  # Only first 3 counts
    print(f"Flashing {count} times")

Output:

["Red", "Yellow", "Green"]
["Blue", "White"]
["White", "Blue", "Green", "Yellow", "Red"]
Flashing 2 times
Flashing 3 times
Flashing 4 times

The Join Method

Converting lists to strings

led_names = ["Red", "Yellow", "Green"]

# Join with commas
colors_text = ", ".join(led_names)
print(colors_text)  # "Red, Yellow, Green"

# Join with different separators
dash_format = " - ".join(led_names)
print(dash_format)  # "Red - Yellow - Green"

# Useful for display summaries
print(f"LEDs used: {', '.join(led_names)}")

Output:

Red, Yellow, Green
Red - Yellow - Green
LEDs used: Red, Yellow, Green

Modulo with Lists

Cycling through limited lists safely

The Problem in Lab 4:

pattern_names = ["Chase", "All Blink", "Reverse Chase", "Wave", "Pulse"]
# User wants 8 patterns, but we only have 5 types!

# This crashes at pattern_num = 5
for pattern_num in range(8):
    pattern_name = pattern_names[pattern_num]  # IndexError!

Solution with Modulo:

for pattern_num in range(8):
    pattern_index = pattern_num % len(pattern_names)  # Always 0-4
    print(f"Pattern {pattern_num + 1}: {pattern_names[pattern_index]}")

Output:

Pattern 1: Chase    (0 % 5 = 0)
Pattern 2: All Blink (1 % 5 = 1)
Pattern 3: Reverse Chase (2 % 5 = 2)
Pattern 4: Wave     (3 % 5 = 3)
Pattern 5: Pulse    (4 % 5 = 4)
Pattern 6: Chase    (5 % 5 = 0) ← Cycles back!
Pattern 7: All Blink (6 % 5 = 1)
Pattern 8: Reverse Chase (7 % 5 = 2)

Why modulo? It’s elegant, safe, and handles infinite cycling automatically!

Adding Items to Lists

Growing your lists

# Start with a list
colors = ["red", "blue"]
print(f"Original: {colors}")

# Add one item to the end
colors.append("green")
print(f"After append: {colors}")

# Insert item at specific position
colors.insert(1, "yellow")  # Insert at index 1
print(f"After insert: {colors}")

Output:

Original: ['red', 'blue']
After append: ['red', 'blue', 'green']
After insert: ['red', 'yellow', 'blue', 'green']

Key methods: - list.append(item) adds to the end - list.insert(index, item) adds at specific position

Removing Items from Lists

Making lists smaller

fruits = ["apple", "banana", "orange", "banana"]
print(f"Original: {fruits}")

# Remove by value (first occurrence)
fruits.remove("banana")
print(f"After remove: {fruits}")

# Remove by index
removed = fruits.pop(1)  # Remove index 1
print(f"Removed '{removed}': {fruits}")

# Remove last item
last = fruits.pop()
print(f"Removed '{last}': {fruits}")

Output:

Original: ['apple', 'banana', 'orange', 'banana']
After remove: ['apple', 'orange', 'banana']
Removed 'orange': ['apple', 'banana']
Removed 'banana': ['apple']

Key methods: - list.remove(item) removes first occurrence of item - list.pop(index) removes and returns item at index - list.pop() removes and returns last item

Checking if Items are in Lists

Finding what you’re looking for

fruits = ["apple", "banana", "orange"]

# Check if item exists
if "banana" in fruits:
    print("We have bananas!")

if "grape" not in fruits:
    print("No grapes available")

# Find the position of an item
position = fruits.index("orange")
print(f"Orange is at index {position}")

Output:

We have bananas!
No grapes available
Orange is at index 2

Key operators: - item in list - True if item exists - item not in list - True if item doesn’t exist - list.index(item) - Returns position of item