Python Chapter 5: Collections

Lists & Tuples - Interactive Learning Tool

Welcome to Collections: Lists & Tuples

Collections are fundamental data structures in Python that allow you to store multiple values in a single variable. This chapter covers two essential collection types:

Lists

Mutable, ordered sequences

  • Can be modified after creation
  • Created with square brackets: [1, 2, 3]
  • Support indexing and slicing
  • Rich set of built-in methods

Tuples

Immutable, ordered sequences

  • Cannot be modified after creation
  • Created with parentheses: (1, 2, 3)
  • Support indexing and slicing
  • More memory efficient than lists

Key Concepts Covered

Creation & Access

Learn how to create lists and tuples, access elements using indexes, and slice sequences.

List Methods

Master append(), extend(), insert(), remove(), pop(), sort(), and reverse().

Comprehensions

Build lists efficiently using list comprehension syntax.

Advanced Functions

Explore enumerate(), zip(), and shallow vs deep copying.

# Quick Examples
# Creating a list
fruits = ['apple', 'banana', 'cherry']

# Creating a tuple
coordinates = (10, 20)

# List comprehension
squares = [x**2 for x in range(5)]

# Tuple unpacking
x, y = coordinates

Interactive List Visualizer Live Demo

Visualize how lists work with indexing and slicing operations.

Your List:

Indexing

Result will appear here
Tip: Python uses zero-based indexing. Use negative indexes to count from the end: -1 is the last element.

Slicing

Result will appear here
Syntax: list[start:end:step] - end is exclusive!
# Indexing Examples
my_list = [10, 20, 30, 40, 50]
my_list[0] # 10 (first element)
my_list[-1] # 50 (last element)
my_list[2] # 30 (third element)

# Slicing Examples
my_list[1:4] # [20, 30, 40]
my_list[:3] # [10, 20, 30] (first 3)
my_list[2:] # [30, 40, 50] (from index 2 onwards)
my_list[::2] # [10, 30, 50] (every 2nd element)

List Methods Playground Interactive

Experiment with list methods and see the results in real-time.

Current List:

Initialize List

Choose Method

Output will appear here

Method Reference

append(item)

Adds an item to the end of the list.

lst.append(5)

extend(iterable)

Adds all items from another iterable.

lst.extend([4, 5])

insert(i, item)

Inserts item at the specified index.

lst.insert(0, 'x')

remove(item)

Removes the first occurrence of item.

lst.remove('x')

pop(index)

Removes and returns item at index (default: -1).

item = lst.pop()

sort()

Sorts the list in place.

lst.sort()

reverse()

Reverses the list in place.

lst.reverse()

clear()

Removes all items from the list.

lst.clear()

List Comprehension Builder Visual Tool

Build list comprehensions visually and understand their structure.

Build Your Comprehension

Generated Comprehension:

[x * 2 for x in range(5)]

Result:

Click "Build & Execute" to see the result

Common Patterns

# Basic comprehension
squares = [x**2 for x in range(10)]
# [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

# With condition
evens = [x for x in range(10) if x % 2 == 0]
# [0, 2, 4, 6, 8]

# Transform strings
names = ['alice', 'bob', 'charlie']
upper_names = [name.upper() for name in names]
# ['ALICE', 'BOB', 'CHARLIE']

# Nested comprehension
matrix = [[1, 2, 3], [4, 5, 6]]
flattened = [num for row in matrix for num in row]
# [1, 2, 3, 4, 5, 6]
Performance Tip: List comprehensions are generally faster than equivalent for loops because they're optimized at the C level in Python's implementation.

Tuples: Immutable Sequences Comparison

List vs Tuple Comparison

Feature List Tuple
Syntax [1, 2, 3] (1, 2, 3)
Mutability Mutable (can be changed) Immutable (cannot be changed)
Methods Many (append, remove, etc.) Few (count, index only)
Performance Slower Faster
Memory More memory Less memory
Use Case When data changes When data is constant

Tuple Operations

Create Tuple

Tuple info will appear here

Tuple Unpacking

Unpacking result will appear here
# Creating tuples
point = (10, 20)
singleton = (42,) # Note the comma!
empty = ()

# Tuple unpacking
x, y = point # x=10, y=20

# Extended unpacking
first, *middle, last = (1, 2, 3, 4, 5)
# first=1, middle=[2,3,4], last=5

# Tuples as dictionary keys (lists can't do this!)
locations = {}
locations[(0, 0)] = 'origin'
locations[(1, 2)] = 'point A'

# Returning multiple values from a function
def get_coordinates():
    return (10, 20) # Returns a tuple

x, y = get_coordinates()
When to use tuples:
  • For data that shouldn't change (coordinates, RGB colors, etc.)
  • As dictionary keys (must be immutable)
  • For function return values with multiple items
  • When you need better performance and lower memory usage

Advanced Topics enumerate, zip, copying

enumerate() - Loop with Index

Result will appear here
# enumerate() gives you index and value
fruits = ['apple', 'banana', 'cherry']
for index, fruit in enumerate(fruits):
    print(f"{index}: {fruit}")

# Output:
# 0: apple
# 1: banana
# 2: cherry

# Start from different index
for index, fruit in enumerate(fruits, start=1):
    print(f"{index}: {fruit}") # 1: apple, 2: banana, ...

zip() - Combine Multiple Lists

Result will appear here
# zip() combines multiple iterables
names = ['Alice', 'Bob', 'Charlie']
ages = [25, 30, 35]
cities = ['NYC', 'LA', 'Chicago']

for name, age, city in zip(names, ages, cities):
    print(f"{name} is {age} years old and lives in {city}")

# Create dictionary from two lists
keys = ['a', 'b', 'c']
values = [1, 2, 3]
dictionary = dict(zip(keys, values)) # {'a': 1, 'b': 2, 'c': 3}

Copying Lists: Shallow vs Deep

Shallow Copy

Click to see demonstration

Deep Copy

Click to see demonstration
# Shallow copy - copies references
original = [1, 2, [3, 4]]
shallow = original.copy() # or original[:]
shallow[0] = 100
shallow[2][0] = 999
# original = [1, 2, [999, 4]] <- nested list affected!
# shallow = [100, 2, [999, 4]]

# Deep copy - copies everything recursively
import copy
original = [1, 2, [3, 4]]
deep = copy.deepcopy(original)
deep[0] = 100
deep[2][0] = 999
# original = [1, 2, [3, 4]] <- unchanged!
# deep = [100, 2, [999, 4]]

Common Patterns

Find Maximum

max_val = max(my_list)

Returns the largest element

Find Minimum

min_val = min(my_list)

Returns the smallest element

Sum All Elements

total = sum(my_list)

Adds all numeric elements

Check Existence

if item in my_list:

Check if item exists

Length

size = len(my_list)

Get number of elements

All/Any

all([True, True])

Check if all/any are True

Knowledge Check Quiz 10 Questions

Test your understanding of lists and tuples!

Course Home