Python 3 — Lists & Tuples

🐍 Python 3 🟢 Lesson 8 📅 July 2026

Lists are Python's most versatile data structure. They store ordered, mutable sequences of any data type. Tuples are similar but immutable — once created, they cannot change. Together, they cover almost all your sequential data storage needs.

1 Creating & Accessing Lists

Lists are created with square brackets []. Items are accessed by their index, starting from 0:

Python 3 — List Basics▶ Run Code
# Creating lists
fruits = ["apple", "banana", "cherry", "mango"]
numbers = [10, 20, 30, 40, 50]
mixed = ["Python", 3, True, 3.14, None]

# Accessing by positive index (0-based)
print(fruits[0])    # apple
print(fruits[2])    # cherry

# Negative indexing (from end)
print(fruits[-1])   # mango (last item)
print(fruits[-2])   # cherry (second from last)

# Length
print(len(fruits))  # 4

# Check membership
print("banana" in fruits)   # True
print("grape" not in fruits) # True
2 List Slicing

Slicing extracts a portion of a list: list[start:stop:step]

Python 3 — Slicing▶ Run Code
nums = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

print(nums[2:6])     # [2, 3, 4, 5] (index 2 to 5)
print(nums[:4])      # [0, 1, 2, 3] (first 4)
print(nums[6:])      # [6, 7, 8, 9] (from index 6)
print(nums[-3:])     # [7, 8, 9] (last 3)
print(nums[::2])     # [0, 2, 4, 6, 8] (every 2nd)
print(nums[::-1])    # [9, 8, 7, ..., 0] (reversed!)
3 Modifying Lists

Lists are mutable — you can add, remove, and change items after creation:

MethodDescriptionExample
append(x)Add to endlist.append(5)
insert(i, x)Insert at indexlist.insert(1, "a")
extend(lst)Add all items from another listlist.extend([4,5,6])
remove(x)Remove first occurrence of xlist.remove("a")
pop(i)Remove & return item at indexlist.pop(0)
clear()Remove all itemslist.clear()
Python 3 — List Methods▶ Run Code
students = ["Alice", "Bob", "Charlie"]

students.append("Diana")          # Add to end
print(students)  # ['Alice', 'Bob', 'Charlie', 'Diana']

students.insert(1, "Eve")         # Insert at index 1
print(students)  # ['Alice', 'Eve', 'Bob', 'Charlie', 'Diana']

students.remove("Bob")            # Remove by value
print(students)  # ['Alice', 'Eve', 'Charlie', 'Diana']

last = students.pop()             # Remove last, returns it
print(f"Removed: {last}")        # Removed: Diana

students[0] = "Alex"              # Modify by index
print(students)
4 Sorting & Ordering
Python 3 — Sorting▶ Run Code
scores = [85, 42, 97, 13, 76, 55]

# sort() modifies in place
scores.sort()
print(scores)                 # [13, 42, 55, 76, 85, 97]

scores.sort(reverse=True)
print(scores)                 # [97, 85, 76, 55, 42, 13]

# sorted() returns new list, original unchanged
names = ["Charlie", "Alice", "Bob", "Diana"]
sorted_names = sorted(names)
print(sorted_names)           # ['Alice', 'Bob', 'Charlie', 'Diana']
print(names)                  # Original unchanged

# Sort by length
words = ["banana", "fig", "cherry", "apple", "kiwi"]
words.sort(key=len)
print(words)                  # ['fig', 'kiwi', 'apple', 'banana', 'cherry']

# reverse() — reverses list in place
scores.reverse()
print(scores)
5 Useful List Functions
Python 3 — List Functions▶ Run Code
numbers = [3, 7, 1, 9, 4, 6, 2, 8, 5]

print(len(numbers))       # 9 — length
print(sum(numbers))       # 45 — total
print(min(numbers))       # 1 — minimum
print(max(numbers))       # 9 — maximum
print(numbers.count(7))   # 1 — how many times 7 appears
print(numbers.index(9))   # 3 — index of value 9

# List from range
evens = list(range(0, 11, 2))
print(evens)  # [0, 2, 4, 6, 8, 10]

# Concatenate lists
a = [1, 2, 3]
b = [4, 5, 6]
c = a + b
print(c)      # [1, 2, 3, 4, 5, 6]

# Repeat list
zeros = [0] * 5
print(zeros)  # [0, 0, 0, 0, 0]
6 Tuples — Immutable Sequences

Tuples are like lists but immutable (cannot be changed after creation). Created with parentheses ():

FeatureList []Tuple ()
Mutable✅ Yes❌ No
PerformanceSlowerFaster
Use caseData that changesFixed data (coordinates, RGB)
Dict key❌ Cannot use✅ Can use as key
Python 3 — Tuples▶ Run Code
# Creating tuples
point = (10, 20)           # 2D coordinate
rgb_red = (255, 0, 0)      # RGB color
months = ("Jan", "Feb", "Mar", "Apr")

# Accessing (same as lists)
print(point[0])    # 10
print(months[-1])  # Apr
print(len(months)) # 4

# Tuple unpacking
x, y = point
print(f"x={x}, y={y}")  # x=10, y=20

r, g, b = rgb_red
print(f"R={r}, G={g}, B={b}")

# Single element tuple (note trailing comma!)
single = (42,)
print(type(single))  # <class 'tuple'>
not_tuple = (42)     # This is just int 42!
print(type(not_tuple))  # <class 'int'>
7 Nested Lists (2D Arrays)
Python 3 — Nested Lists▶ Run Code
# 2D matrix (list of lists)
matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

# Access: matrix[row][column]
print(matrix[0][0])  # 1 (top-left)
print(matrix[1][2])  # 6 (row 1, col 2)
print(matrix[2][1])  # 8 (row 2, col 1)

# Iterate through 2D matrix
for row in matrix:
    for item in row:
        print(item, end=" ")
    print()

# Modify a cell
matrix[0][0] = 99
print(matrix[0])  # [99, 2, 3]
8 Coding Challenge

Write a program that:

  • Creates a list of 8 student scores
  • Calculates and prints: total, average, highest score, lowest score
  • Sorts the list and prints it in ascending and descending order
  • Creates a "grade list" using a loop: A (≥90), B (≥80), C (≥70), F (otherwise)
  • Stores (score, grade) pairs as tuples in a list
  • Prints each student's score and grade using enumerate()