Python Lists, Tuples, and Dictionaries

📑 Navigation

Modifying Lists During Iteration • List Comprehensions • List Aliases and Copying • Multi-Dimensional Lists • Tuples • Dictionaries • Dictionary Comprehensions • Variable Scope • Python Memory Optimization • Key Takeaways

What is a List?

Definition

A list is an ordered, mutable collection of items in Python. Think of it as a container that can hold multiple values in a specific sequence.

shopping_list = ['apple', 'banana', 'milk', 'bread']
numbers = [1, 2, 3, 4, 5]
mixed = [1, 'hello', 3.14, True]  # Can contain different types!

Key Characteristics

Ordered: Items maintain their position. ['apple', 'banana'] is different from ['banana', 'apple'].

Mutable: You can change, add, or remove items after creation.

Indexed: Access items by position using list[0], list[1], etc. (starts at 0).

Allow duplicates: The same value can appear multiple times.

Mixed types: Lists can contain different data types (strings, numbers, booleans, even other lists!).

Creating Lists

# Empty list
empty_list = []

# List with items
fruits = ['apple', 'banana', 'orange']

# Using the list() constructor
numbers = list(range(5))  # [0, 1, 2, 3, 4]

Basic List Operations

Accessing Items

fruits = ['apple', 'banana', 'orange', 'grape']

print(fruits[0])   # 'apple' (first item)
print(fruits[-1])  # 'grape' (last item)
print(fruits[1:3]) # ['banana', 'orange'] (slicing)

Remember: Python uses zero-based indexing — the first item is at index 0!