Part 3: Lists

Kerry Back, Rice University

Lists

Lists are ordered collections of items that can be of any type.

Key features: - Created with square brackets [], items separated by commas - Zero-based indexing (first element is at index 0) - Can contain mixed data types - Are mutable (can be changed after creation)

# List of numbers
numbers = [1, 2, 3, 4, 5]

# List of strings
fruits = ["apple", "banana", "cherry"]

# Mixed types
mixed = [1, "hello", 3.14, True]

Practice: Creating Lists

Exercise 1 (with Gemini): Ask Gemini to “write Python code that creates a list of three colors and prints it”

Exercise 2 (on your own): Type my_list = [10, 20, 30] then print(my_list) and run it.

Concatenating Lists

Lists can be combined using the + operator:

list1 = [1, 2, 3]
list2 = [4, 5, 6]

combined = list1 + list2
print(combined)

# Direct concatenation
result = ["a", "b"] + ["c", "d"]
print(result)
[1, 2, 3, 4, 5, 6]
['a', 'b', 'c', 'd']

Practice: Concatenating Lists

Exercise 1 (with Gemini): Ask Gemini to “write Python code that concatenates [1, 2, 3] and [4, 5, 6]”

Exercise 2 (on your own): Type print([10, 20] + [30, 40]) and run it.

List Methods

Lists have useful methods to modify or query them:

  • .append(item) - adds item to the end
  • .insert(index, item) - inserts item at position
  • .remove(item) - removes first occurrence
  • .pop() - removes and returns last item
  • .count(item) - counts occurrences
  • .sort() - sorts in place
  • .reverse() - reverses order

Methods that Operate In Place

Important difference from string methods:

Most list methods modify the list directly instead of returning a new list.

my_list = [3, 1, 4, 1, 5]
print("Original:", my_list)

my_list.append(9)
print("After append:", my_list)

my_list.sort()
print("After sort:", my_list)
Original: [3, 1, 4, 1, 5]
After append: [3, 1, 4, 1, 5, 9]
After sort: [1, 1, 3, 4, 5, 9]

Note: Methods like .append() and .sort() return None, not a new list!

Practice: List Methods

Exercise 1 (with Gemini): Ask Gemini to “write Python code that creates a list [5, 2, 8] and sorts it”

Exercise 2 (on your own): Type nums = [1, 2, 3] then nums.append(4) then print(nums) and run it.

More List Methods

colors = ["red", "blue", "green", "blue", "yellow"]

# Insert at position
colors.insert(1, "purple")
print("After insert:", colors)

# Count occurrences
print("Count of 'blue':", colors.count("blue"))

# Remove first occurrence
colors.remove("blue")
print("After remove:", colors)

# Pop last item
last = colors.pop()
print("Popped:", last)
print("Remaining:", colors)
After insert: ['red', 'purple', 'blue', 'green', 'blue', 'yellow']
Count of 'blue': 2
After remove: ['red', 'purple', 'green', 'blue', 'yellow']
Popped: yellow
Remaining: ['red', 'purple', 'green', 'blue']

Practice: More Methods

Exercise 1 (with Gemini): Ask Gemini to “write Python code that removes the first ‘apple’ from a list of fruits”

Exercise 2 (on your own): Type items = [1, 2, 3] then print(items.pop()) and run it.

Indexing

Access individual elements using square brackets with an index:

colors = ["red", "green", "blue", "yellow", "purple"]

print("First element [0]:", colors[0])
print("Third element [2]:", colors[2])
print("Last element [-1]:", colors[-1])
print("Second to last [-2]:", colors[-2])
First element [0]: red
Third element [2]: blue
Last element [-1]: purple
Second to last [-2]: yellow

Negative indices count from the end: -1 is last, -2 is second to last, etc.

Practice: Indexing

Exercise 1 (with Gemini): Ask Gemini to “write Python code that gets the last element from a list using negative indexing”

Exercise 2 (on your own): Type nums = [10, 20, 30, 40] then print(nums[0]) and run it.

Slicing

Extract a portion of a list using slicing [start:end]:

colors = ["red", "green", "blue", "yellow", "purple", "orange"]

print("First three [0:3]:", colors[0:3])
print("Elements 2-4 [2:5]:", colors[2:5])
print("First three [:3]:", colors[:3])
print("From index 3 [3:]:", colors[3:])
First three [0:3]: ['red', 'green', 'blue']
Elements 2-4 [2:5]: ['blue', 'yellow', 'purple']
First three [:3]: ['red', 'green', 'blue']
From index 3 [3:]: ['yellow', 'purple', 'orange']

Note: [start:end] includes start but excludes end

Practice: Slicing

Exercise 1 (with Gemini): Ask Gemini to “write Python code that gets the first three elements from a list using slicing”

Exercise 2 (on your own): Type letters = ['a', 'b', 'c', 'd', 'e'] then print(letters[1:4]) and run it.

List Unpacking

Extract all elements and assign to variables in one step:

my_list = [10, 20, 30]

# Unpack into three variables
x, y, z = my_list
print(f"x={x}, y={y}, z={z}")

# Must match number of elements
fruits = ["apple", "banana"]
first, second = fruits
print(f"First: {first}, Second: {second}")
x=10, y=20, z=30
First: apple, Second: banana

Important: Number of variables must match number of list elements!

Practice: List Unpacking

Exercise 1 (with Gemini): Ask Gemini to “write Python code that unpacks a list of two numbers into variables x and y”

Exercise 2 (on your own): Type a, b, c = [1, 2, 3] then print(a, b, c) and run it.

Summary

  • Lists are ordered, mutable collections created with []
  • Concatenate with + operator
  • Methods like .append(), .sort(), .remove() modify lists in place
  • Indexing with [i] - use negative indices to count from end
  • Slicing with [start:end] to get sublists
  • Unpacking assigns all elements to variables at once

Lists are fundamental to Python - you’ll use them constantly!