This chapter introduces tuples, lists, and dictionaries.
Lists are ordered collections of items that can be of different types and are mutable (changeable). Lists are one of the four built-in data structures in Python.
You can create lists using square brackets or the list() constructor:
# Empty list empty_list = [] # List with items numbers = [1, 2, 3, 4, 5] fruits = ["apple", "banana", "orange"] mixed = [1, "hello", 3.14, True]
Access list elements using index starting from 0:
fruits = ["apple", "banana", "orange"] print(fruits[0]) # "apple" print(fruits[-1]) # "orange" (last element) # Slicing print(fruits[1:3]) # ["banana", "orange"]
fruits[1] = "grape"fruits.append("kiwi")fruits.insert(1, "pear")fruits.remove("banana")del fruits[2]last_fruit = fruits.pop()Common list methods include:
The sorted() function returns a new sorted list:
numbers = [3, 1, 4, 1, 5] sorted_numbers = sorted(numbers) print(sorted_numbers) # [1, 1, 3, 4, 5]
Dictionaries are unordered collections of key-value pairs. They allow you to store and retrieve data using descriptive keys instead of numerical indexes like lists.
Tuples are immutable ordered sequences, similar to lists but cannot be modified after creation. They are defined using parentheses:
# Creating tuples
empty_tuple = ()
single_item = ("hello",)
coordinates = (3.14, 2.71, 1.41)
person = ("Alice", 30, "Engineer")
Once created, tuple elements cannot be changed:
coordinates = (3.14, 2.71, 1.41) # coordinates[0] = 3.0 # TypeError! # But you can create new tuples coordinates = (3.0,) + coordinates[1:] # Creates new tuple
Multiple assignment works well with tuples:
name, age, profession = ("Alice", 30, "Engineer")
print(name, age, profession) # Alice 30 Engineer
# Swapping values
a = 5
b = 10
a, b = b, a # a=10, b=5
Compact way to create new lists from existing ones:
# Create squares of numbers 1-5 squares = [x**2 for x in range(1, 6)] print(squares) # [1, 4, 9, 16, 25] # With condition even_squares = [x**2 for x in range(1, 11) if x % 2 == 0] print(even_squares) # [4, 16, 36, 64, 100]
Shallow vs Deep Copy:
original = [1, 2, [3, 4]] # Shallow copy - nested lists share references shallow = original[:] shallow[2][0] = 99 print(original) # [1, 2, [99, 4]] import copy deep = copy.deepcopy(original) deep[2][0] = 88 print(original) # Still [1, 2, [99, 4]]
# Empty dictionary
empty_dict = {}
# Dictionary with items
person = {
"name": "Alice",
"age": 30,
"profession": "Engineer"
}
# Using dict() constructor
coordinates = dict(x=10, y=20, z=30)
person = {"name": "Alice", "age": 30}
print(person["name"]) # Alice
# Using get() to avoid KeyError
print(person.get("salary", "Not specified")) # Not specified
# Check if key exists
if "name" in person:
print("Name found:", person["name"])
person = {"name": "Alice", "age": 30}
# Add new key-value pair
person["profession"] = "Engineer"
# Update existing value
person["age"] = 31
# Remove items
del person["age"]
profession = person.pop("profession", "Not specified")
# Get all keys/values/items
keys = person.keys()
values = person.values()
items = person.items()
# Debug dictionary operations
person = {"name": "Alice", "age": 30}
# Check keys before access
key = "salary"
if key in person:
print(f"{key}: {person[key]}")
else:
print(f"{key} not found")
# Use get() for safety
salary = person.get("salary", "Not available")
print(f"Salary: {salary}")
# Print dictionary contents for debugging
print("Person dict:", person)
print("Keys:", list(person.keys()))
print("Values:", list(person.values()))
This chapter introduces tuples, lists, and dictionaries, three fundamental data structures in Python. Lists are mutable sequences, tuples are immutable sequences, and dictionaries are unordered collections of key-value pairs.
These data structures form the backbone of most Python programs, enabling complex data manipulation and storage.