← Back to Python Chapter 5: Collections
0% Complete

Lists: Ordered Collections

A list is an ordered, mutable collection of items. Lists can contain any type of data and are one of Python's most versatile data structures.

Creating Lists

creating_lists.py Python
# Empty list empty = [] # List with items fruits = ["apple", "banana", "cherry"] numbers = [1, 2, 3, 4, 5] # Mixed types mixed = [42, "hello", 3.14, True] # Nested lists matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] print(fruits) print(len(fruits))
['apple', 'banana', 'cherry'] 3

Accessing Elements (Indexing)

Lists use zero-based indexing. Use negative indices to access from the end:

indexing.py Python
colors = ["red", "green", "blue", "yellow"] print(colors[0]) # First element print(colors[2]) # Third element print(colors[-1]) # Last element print(colors[-2]) # Second to last
red blue yellow green

List Slicing

Use [start:stop:step] to extract parts of a list:
colors[1:3] → ['green', 'blue']
colors[:2] → ['red', 'green']
colors[::2] → ['red', 'blue'] (every 2nd item)
colors[::-1] → ['yellow', 'blue', 'green', 'red'] (reversed)

Modifying Lists

Lists are mutable - you can change their contents:

modifying.py Python
numbers = [1, 2, 3, 4, 5] # Change single element numbers[0] = 10 print(numbers) # [10, 2, 3, 4, 5] # Change multiple elements (slice assignment) numbers[1:3] = [20, 30] print(numbers) # [10, 20, 30, 4, 5]
[10, 2, 3, 4, 5] [10, 20, 30, 4, 5]

Lab Exercise 1: List Basics

Beginner

Instructions

Practice creating and accessing list elements.

Your Task

Create a list called scores with values [85, 92, 78, 95, 88]. Print the first score, last score, and the middle three scores using slicing.

Code Editor
Output
Click "Run Code" to see output...

Checkpoint: List Basics Complete!

You know how to create and access lists. Let's learn list methods!

List Methods: Powerful Operations

Python lists come with built-in methods for adding, removing, and manipulating elements.

Adding Elements

adding.py Python
fruits = ["apple", "banana"] # append() - Add to end fruits.append("cherry") print(fruits) # ['apple', 'banana', 'cherry'] # insert() - Add at specific position fruits.insert(1, "blueberry") print(fruits) # ['apple', 'blueberry', 'banana', 'cherry'] # extend() - Add multiple items fruits.extend(["date", "elderberry"]) print(fruits)
['apple', 'banana', 'cherry'] ['apple', 'blueberry', 'banana', 'cherry'] ['apple', 'blueberry', 'banana', 'cherry', 'date', 'elderberry']

Removing Elements

removing.py Python
numbers = [1, 2, 3, 4, 5, 3] # remove() - Remove first occurrence of value numbers.remove(3) print(numbers) # [1, 2, 4, 5, 3] # pop() - Remove and return element at index last = numbers.pop() # Remove last (default) second = numbers.pop(1) # Remove at index 1 print(f"Removed: {last}, {second}") print(numbers) # clear() - Remove all elements numbers.clear() print(numbers) # []
[1, 2, 4, 5, 3] Removed: 3, 2 [1, 4, 5] []

Sorting and Reversing

sorting.py Python
numbers = [3, 1, 4, 1, 5, 9, 2] # sort() - Sorts in place numbers.sort() print(numbers) # [1, 1, 2, 3, 4, 5, 9] # sort(reverse=True) - Descending order numbers.sort(reverse=True) print(numbers) # [9, 5, 4, 3, 2, 1, 1] # reverse() - Reverse the list numbers.reverse() print(numbers) # sorted() - Returns new sorted list (original unchanged) original = [3, 1, 2] new_sorted = sorted(original) print(f"Original: {original}, Sorted: {new_sorted}")
[1, 1, 2, 3, 4, 5, 9] [9, 5, 4, 3, 2, 1, 1] [1, 1, 2, 3, 4, 5, 9] Original: [3, 1, 2], Sorted: [1, 2, 3]

Other Useful Methods

list.count(x) - Count occurrences of x
list.index(x) - Find index of first x
list.copy() - Create a shallow copy
x in list - Check if x exists (returns True/False)

Lab Exercise 2: List Manipulation

Intermediate

Instructions

Practice using list methods to manipulate data.

Your Task

Start with tasks = ["email", "meeting", "lunch"]. Add "report" to the end, insert "coffee" at the beginning, remove "lunch", and print the final sorted list.

Code Editor
Output
Click "Run Code" to see output...

Checkpoint: List Methods Mastered!

You can manipulate lists like a pro. Now let's learn about tuples!

Tuples: Immutable Sequences

A tuple is like a list, but immutable - once created, it cannot be changed. Tuples are faster than lists and are used for data that shouldn't be modified.

Creating Tuples

tuples.py Python
# Using parentheses coordinates = (10, 20) colors = ("red", "green", "blue") # Without parentheses (tuple packing) point = 5, 10, 15 # Single element tuple (needs trailing comma!) single = (42,) # This is a tuple not_tuple = (42) # This is just an integer! print(type(single)) print(type(not_tuple))
<class 'tuple'> <class 'int'>

Tuple Operations

tuple_ops.py Python
person = ("Alice", 25, "Engineer") # Indexing (same as lists) print(person[0]) # Alice print(person[-1]) # Engineer # Slicing print(person[1:]) # (25, 'Engineer') # Tuple unpacking name, age, job = person print(f"{name} is {age} and works as {job}") # Methods: count() and index() nums = (1, 2, 2, 3, 2) print(f"Count of 2: {nums.count(2)}") print(f"Index of 3: {nums.index(3)}")
Alice Engineer (25, 'Engineer') Alice is 25 and works as Engineer Count of 2: 3 Index of 3: 3

Tuples Are Immutable!

You cannot modify a tuple after creation:
person[1] = 30 → TypeError: 'tuple' object does not support item assignment
If you need to "modify" a tuple, create a new one instead.

When to Use Tuples vs Lists

Use Tuples When... Use Lists When...
Data shouldn't change (coordinates, RGB values) Data will be modified (shopping cart, scores)
Returning multiple values from functions You need to add/remove elements
Dictionary keys (must be immutable) Order matters and data is dynamic
Performance matters (tuples are faster) You need list methods like sort, append

Lab Exercise 3: Tuple Unpacking

Intermediate

Instructions

Practice tuple unpacking - a powerful Python feature!

Your Task

Given student = ("Bob", 21, "Computer Science", 3.8), unpack it into variables name, age, major, gpa and print a formatted message.

Code Editor
Output
Click "Run Code" to see output...

Checkpoint: Tuples Understood!

You know when to use tuples. Now let's explore sets!

Sets: Unique Collections

A set is an unordered collection of unique elements. Sets automatically remove duplicates and provide fast membership testing.

Creating Sets

sets.py Python
# Using curly braces colors = {"red", "green", "blue"} # From a list (removes duplicates!) numbers = set([1, 2, 2, 3, 3, 3]) print(numbers) # {1, 2, 3} # Empty set (NOT {} - that's an empty dict!) empty = set() # Sets are unordered - no indexing! # colors[0] # Error!
{1, 2, 3}

Set Operations

set_ops.py Python
a = {1, 2, 3, 4} b = {3, 4, 5, 6} # Union - all elements from both print(a | b) # {1, 2, 3, 4, 5, 6} print(a.union(b)) # Same thing # Intersection - elements in both print(a & b) # {3, 4} print(a.intersection(b)) # Same thing # Difference - elements in a but not b print(a - b) # {1, 2} print(a.difference(b)) # Same thing # Symmetric difference - elements in either, but not both print(a ^ b) # {1, 2, 5, 6} print(a.symmetric_difference(b)) # Same thing
{1, 2, 3, 4, 5, 6} {1, 2, 3, 4, 5, 6} {3, 4} {3, 4} {1, 2} {1, 2} {1, 2, 5, 6} {1, 2, 5, 6}

Set Methods

set.add(x) - Add element x
set.remove(x) - Remove x (error if not found)
set.discard(x) - Remove x (no error if not found)
x in set - Fast membership test (O(1) average)
set.issubset(other) - Check if set ⊆ other

Practical Use Case

practical_set.py Python
# Remove duplicates from a list emails = ["a@b.com", "c@d.com", "a@b.com", "e@f.com"] unique_emails = list(set(emails)) print(f"Unique emails: {unique_emails}") # Fast membership testing allowed_users = {"alice", "bob", "charlie"} user = "bob" if user in allowed_users: print("Access granted!")
Unique emails: ['a@b.com', 'e@f.com', 'c@d.com'] Access granted!

Lab Exercise 4: Set Operations

Intermediate

Instructions

Use set operations to analyze data.

Your Task

Given python_students = {"Alice", "Bob", "Charlie"} and java_students = {"Bob", "David", "Eve"}, find: students in both classes, students only in Python, and all unique students.

Code Editor
Output
Click "Run Code" to see output...

Checkpoint: Sets Mastered!

You understand sets. Let's learn list comprehensions!

List Comprehensions: Pythonic Power

List comprehensions are a concise way to create lists. They combine loops and conditions into a single line - very Pythonic!

Basic Syntax

comprehension_basic.py Python
# Traditional loop squares_loop = [] for x in range(5): squares_loop.append(x ** 2) print(squares_loop) # [0, 1, 4, 9, 16] # List comprehension (same result!) squares_comp = [x ** 2 for x in range(5)] print(squares_comp) # [0, 1, 4, 9, 16]
[0, 1, 4, 9, 16] [0, 1, 4, 9, 16]

Comprehension Pattern

[expression for item in iterable]
With condition: [expression for item in iterable if condition]
The expression is evaluated for each item that passes the condition.

With Conditions

comprehension_conditions.py Python
# Even numbers only evens = [x for x in range(10) if x % 2 == 0] print(evens) # [0, 2, 4, 6, 8] # Transform and filter words = ["hello", "WORLD", "Python"] upper_long = [w.upper() for w in words if len(w) > 5] print(upper_long) # ['PYTHON'] # If-else (note: different position!) labels = ["even" if x % 2 == 0 else "odd" for x in range(5)] print(labels) # ['even', 'odd', 'even', 'odd', 'even']
[0, 2, 4, 6, 8] ['PYTHON'] ['even', 'odd', 'even', 'odd', 'even']

Other Comprehensions

other_comprehensions.py Python
# Set comprehension (uses curly braces) unique_lengths = {len(word) for word in ["hi", "hello", "hey"]} print(unique_lengths) # {2, 3, 5} # Dictionary comprehension squares_dict = {x: x**2 for x in range(4)} print(squares_dict) # {0: 0, 1: 1, 2: 4, 3: 9} # Generator expression (uses parentheses, lazy evaluation) sum_squares = sum(x**2 for x in range(5)) print(sum_squares) # 30
{2, 3, 5} {0: 0, 1: 1, 2: 4, 3: 9} 30

Lab Exercise 5: Comprehensions

Intermediate

Instructions

Convert traditional loops to list comprehensions.

Your Task

Create a list comprehension that generates the first 10 Fibonacci-like sequence starting with squares: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] (i.e., squares of 1-10).

Code Editor
Output
Click "Run Code" to see output...

Checkpoint: Comprehensions Complete!

You're writing Pythonic code now! Time for the summary.

Chapter 5 Summary

Congratulations! You've mastered Python's core collection types. Let's recap:

Collection Types Comparison

Type Syntax Ordered? Mutable? Duplicates?
List [1, 2, 3] Yes Yes Yes
Tuple (1, 2, 3) Yes No Yes
Set {1, 2, 3} No Yes No

Key Takeaways

Lists

Ordered, mutable. Use for collections that change.

Tuples

Ordered, immutable. Use for fixed data, returns.

Sets

Unique elements, fast lookup. Use for deduplication.

Comprehensions

One-line list creation. Pythonic and efficient.

Chapter 5 Complete!

You've mastered Python collections. Ready to prove your skills?

Take the Chapter 5 Practical Exam