Day 6: Lists & Tuples — Working with Collections

🐍 Day 6: Lists & Tuples — Working with Collections


1. Learning Objectives

By the end of Day 6, you will be able to:

  • Create and use lists — Python's most versatile, mutable collection

  • Create and use tuples — immutable sequences for fixed data

  • Access elements via indexing and slicing

  • Modify lists with append, insert, remove, pop, and more

  • Iterate through lists and tuples with loops

  • Choose between lists and tuples based on your needs


2. Concept Explanation

2.1 Why Collections?

So far, you've stored one value per variable. But what about a class roster? A shopping cart? A list of temperatures? You need a collection — a single variable that holds many values.

Python gives you two primary sequence types today: lists (mutable) and tuples (immutable). Dictionaries and sets come on Day 7.


2.2 Lists — The Swiss Army Knife of Collections

A list is an ordered, mutable (changeable) sequence. It can hold items of any type — even mixed types.

# Creating lists
empty_list = []
numbers = [1, 2, 3, 4, 5]
fruits = ["apple", "banana", "cherry"]
mixed = [42, "hello", 3.14, True]
nested = [[1, 2], [3, 4]]   # Lists inside lists!

Key trait: Lists are mutable — you can change them after creation.


2.3 Accessing Elements — Indexing

Every element in a list has a position (index), starting from 0.

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

print(fruits[0])    # apple (first)
print(fruits[1])    # banana (second)
print(fruits[2])    # cherry (third)
# print(fruits[3]) # IndexError: list index out of range

Negative indexing counts from the end:

print(fruits[-1])   # cherry (last)
print(fruits[-2])   # banana (second-to-last)
print(fruits[-3])   # apple (first)

2.4 Slicing — Extracting Sub-lists

Slicing gives you a new list from a range of indices:

nums = [10, 20, 30, 40, 50]

print(nums[1:4])    # [20, 30, 40] (start at 1, up to but NOT including 4)
print(nums[:3])     # [10, 20, 30] (from beginning to index 2)
print(nums[2:])     # [30, 40, 50] (from index 2 to end)
print(nums[:])      # [10, 20, 30, 40, 50] (entire list — a shallow copy)
print(nums[-3:])    # [30, 40, 50] (last 3 elements)
print(nums[::2])    # [10, 30, 50] (every 2nd element, step=2)
print(nums[::-1])   # [50, 40, 30, 20, 10] (reverse!)

💡 Slicing always returns a new list. It never modifies the original.


2.5 Modifying Lists — Because They're Mutable

Changing an element:

fruits = ["apple", "banana", "cherry"]
fruits[1] = "blueberry"
print(fruits)   # ['apple', 'blueberry', 'cherry']

Adding elements:

# .append() — add to the end
numbers = [1, 2, 3]
numbers.append(4)
print(numbers)  # [1, 2, 3, 4]

# .insert() — insert at a specific index
numbers.insert(0, 0)   # insert 0 at index 0
print(numbers)  # [0, 1, 2, 3, 4]

# .extend() — add multiple items from another list
numbers.extend([5, 6, 7])
print(numbers)  # [0, 1, 2, 3, 4, 5, 6, 7]

Removing elements:

# .remove() — remove by value (first occurrence only)
fruits = ["apple", "banana", "cherry", "banana"]
fruits.remove("banana")
print(fruits)   # ['apple', 'cherry', 'banana']

# .pop() — remove by index and return the removed item
removed = fruits.pop(1)     # removes index 1 ("cherry")
print(fruits)   # ['apple', 'banana']
print(removed)  # cherry

# .pop() without index removes the last item
fruits.pop()
print(fruits)   # ['apple']

# del — delete by index (or the whole list)
del fruits[0]
print(fruits)   # []

# .clear() — remove all items
numbers.clear()
print(numbers)  # []

Other useful operations:

# len() — number of elements
print(len([1, 2, 3]))       # 3

# in — membership test
print("apple" in ["apple", "banana"])   # True
print("grape" in ["apple", "banana"])   # False

# .index() — find the index of a value
print([10, 20, 30].index(20))  # 1

# .count() — count occurrences
print([1, 2, 2, 3, 2].count(2))  # 3

# .sort() — sort in place (modifies original)
nums = [3, 1, 4, 1, 5]
nums.sort()
print(nums)  # [1, 1, 3, 4, 5]

# sorted() — returns a new sorted list (original unchanged)
original = [3, 1, 4]
new = sorted(original)
print(original)  # [3, 1, 4]
print(new)       # [1, 3, 4]

# .reverse() — reverse in place
nums.reverse()
print(nums)  # [5, 4, 3, 1, 1]

2.6 Iterating Through Lists

Lists and for loops are best friends:

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

# Iterate with index using range()
for i in range(len(colors)):
print(f"Index {i}: {colors[i]}")

# Better: enumerate() — gives you (index, value) pairs
for idx, color in enumerate(colors):
print(f"Index {idx}: {color}")

2.7 Tuples — Immutable Lists

A tuple is like a list, but immutable — once created, you cannot change it. Tuples use parentheses () instead of brackets [].

# Creating tuples
point = (3, 4)
person = ("Alice", 28, "Manila")
single_item = (42,) # Comma is necessary for a single-element tuple!
empty = ()
tuple_from_list = tuple([1, 2, 3])

# Accessing (works just like lists)
print(point[0]) # 3
print(person[-1]) # Manila
print(point[0:2]) # (3, 4)

# But you CANNOT modify:
# point[0] = 5 # TypeError: 'tuple' object does not support item assignment

Why use tuples?

  • They're faster than lists (less memory overhead).

  • They're hashable — can be used as dictionary keys (Day 7).

  • They signal intent: "This data shouldn't change."

  • Python itself uses tuples for many built-in features (e.g., return a, b actually returns a tuple).

Tuple unpacking:

# Assign multiple variables at once
coordinates = (10, 20, 30)
x, y, z = coordinates
print(x, y, z) # 10 20 30

# Swap variables without a temp variable
a, b = 5, 10
a, b = b, a
print(a, b) # 10 5

2.8 List vs. Tuple — Decision Guide

Feature List Tuple
Syntax [1, 2, 3] (1, 2, 3)
Mutable? ✅ Yes ❌ No
Speed Slower Faster
Memory More Less
Use as dict key? ❌ No ✅ Yes
Typical use Collections that change Fixed data, constants, coordinates, returns

Rule of thumb: Default to lists. Use tuples when you know the data shouldn't change, or when you need a hashable type.


2.9 Common Mistakes

Mistake Example Fix
Index out of range lst[5] on a list of 5 items Remember indices go 0 to len-1; use -1 for last
Forgetting comma in single-item tuple (42) is just 42 (an int) Use (42,)
Using .append() on a tuple tup.append(1) Tuples don't have .append() — convert to list first
Modifying list while iterating Messes up indices Iterate over a copy: for item in lst[:]:
Assigning slice but not using it lst[1:3] does nothing alone Slice returns new list; assign it back or use .remove() etc.

3. Code Examples

Example 1: Shopping Cart

cart = []

while True:
item = input("Add item (or 'done' to finish): ")
if item.lower() == "done":
break
cart.append(item)
print(f"Cart: {cart}")

print(f"\nYou bought {len(cart)} items: {cart}")

Example 2: Basic Statistics

def calculate_stats(numbers):
"""Return min, max, and average of a list of numbers."""
total = sum(numbers)
avg = total / len(numbers)
return min(numbers), max(numbers), avg

scores = [85, 92, 78, 90, 88]
low, high, average = calculate_stats(scores)
print(f"Min: {low}, Max: {high}, Average: {average:.2f}")

Example 3: List Comprehension Preview (Day 11)

# Traditional way to create a list of squares
squares = []
for x in range(1, 6):
squares.append(x ** 2)
print(squares) # [1, 4, 9, 16, 25]

# List comprehension (compact)
squares = [x ** 2 for x in range(1, 6)]
print(squares) # [1, 4, 9, 16, 25]

4. Hands-On Exercises

Exercise 1: List Creator

Ask the user for 5 names, store them in a list, then print the list. Then print each name on a separate line using a loop.

Exercise 2: Slicing Practice

Given the list nums = [10, 20, 30, 40, 50, 60, 70], write code to produce:

  • The first 4 elements

  • The last 3 elements

  • Every 2nd element

  • The list in reverse order

Exercise 3: To-Do List

Write a program that starts with an empty list. Repeatedly ask the user to [A]dd, [R]emove, [V]iew, or [Q]uit. Implement each option using list methods.

Exercise 4: Tuple Unpacking

Create a tuple with your name, age, and favorite color. Unpack it into three variables and print them individually.

Exercise 5: List Modifier

Given nums = [5, 2, 8, 1, 9], write code to:

  • Append 10

  • Insert 0 at the beginning

  • Remove the value 8

  • Pop the last element and print what was removed

  • Sort the list

  • Print the final list


5. Applied Challenge Task 🏗️

Grade Analyzer

Build a program that:

  1. Asks the user to enter 5 grades (0–100) and stores them in a list.

  2. Uses the list to calculate:

    • Highest grade

    • Lowest grade

    • Average grade

    • Number of passing grades (≥ 60)

  3. Prints a summary:

=== GRADE ANALYSIS ===
Grades: [85, 92, 78, 55, 90]
Highest: 92
Lowest: 55
Average: 80.0
Passing: 4 out of 5
======================

Stretch goals:

  • Sort grades and print them in order (highest to lowest)

  • Allow the user to enter as many grades as they want (stop on "done")

  • Convert the grade list to a tuple and display it (to show you can)

  • Add grade letters alongside each score (90-100: A, etc.)


6. Brief Review Summary

Concept Key Points
List [ ] — mutable, ordered, indexed, can hold any types
Indexing lst[0] first, lst[-1] last; IndexError if out of range
Slicing lst[start:stop:step] returns a new list
Methods .append(), .insert(), .remove(), .pop(), .sort(), and more
Tuple ( ) — immutable, faster, hashable; good for fixed data
Unpacking a, b = (1, 2) or a, b = b, a (swap)
Iteration for item in list: or for idx, item in enumerate(list):
in operator Check membership: if "apple" in fruits:

7. Preview of Next Topic — Day 7

Tomorrow we round out the foundations with two more collection types and a mini-project:

  • Dictionaries — key-value pairs for fast lookups

  • Sets — unique, unordered collections

  • Weekly Mini-Project: A console-based utility app combining everything from Days 1–7


🎯 Your Action Items for Day 6:

  1. ✅ Complete all 5 exercises

  2. ✅ Complete the Grade Analyzer challenge

  3. ✅ Experiment with every list method in the interactive shell

  4. ✅ Create a tuple and try to modify it — observe the error


Comments

Popular posts from this blog

Day 1: Welcome to Python — Your Journey Begins

Python: Your Gateway to Coding Adventures

Day 11: List Comprehensions & Lambda Functions

Earn From the Comfort of Your Home

Build the skills to work comfortably from home, on your own terms.

Get Started Today