Data Structures
Lists, tuples, dictionaries, and sets - Python's built-in data structures.
Lists
- Ordered, mutable collections.
- Can contain mixed data types.
- Access elements by index (starting at 0).
- Support slicing, appending, and more.
# Creating lists
fruits = ["apple", "banana", "cherry"]
numbers = [1, 2, 3, 4, 5]
mixed = [1, "hello", 3.14, True]
# Accessing elements
print(fruits[0]) # apple
print(fruits[-1]) # cherry (last item)
# Slicing
print(numbers[1:4]) # [2, 3, 4]
# Modifying
fruits.append("orange")
fruits.insert(1, "mango")
fruits.remove("banana")
print(fruits)
List Methods
- append(): Add item to end
- insert(): Add item at position
- remove(): Remove first occurrence
- pop(): Remove and return item
- sort(): Sort list in place
- reverse(): Reverse list in place
numbers = [3, 1, 4, 1, 5]
numbers.append(9)
print(numbers) # [3, 1, 4, 1, 5, 9]
numbers.sort()
print(numbers) # [1, 1, 3, 4, 5, 9]
numbers.reverse()
print(numbers) # [9, 5, 4, 3, 1, 1]
last = numbers.pop()
print(last) # 1
print(numbers) # [9, 5, 4, 3, 1]
Tuples
- Ordered, immutable collections.
- Faster than lists for read-only data.
- Use parentheses () instead of brackets [].
- Support unpacking for multiple assignment.
# Creating tuples
point = (10, 20)
rgb = (255, 128, 0)
# Accessing
print(point[0]) # 10
# Unpacking
x, y = point
print(x, y) # 10 20
# Tuples are immutable
# point[0] = 15 # Error!
# Single element tuple needs comma
single = (42,)
Dictionaries
- Key-value pairs (like a real dictionary).
- Keys must be unique and immutable.
- Fast lookup by key.
- Use curly braces {} with key:value pairs.
# Creating dictionaries
person = {
"name": "Alice",
"age": 25,
"city": "New York"
}
# Accessing values
print(person["name"]) # Alice
print(person.get("age")) # 25
# Adding/modifying
person["email"] = "alice@example.com"
person["age"] = 26
# Looping
for key, value in person.items():
print(f"{key}: {value}")
Sets
- Unordered collection of unique elements.
- No duplicates allowed.
- Fast membership testing.
- Support mathematical set operations.
# Creating sets
fruits = {"apple", "banana", "cherry"}
numbers = {1, 2, 3, 3, 4} # Duplicates removed
print(numbers) # {1, 2, 3, 4}
# Adding/removing
fruits.add("orange")
fruits.remove("banana")
# Set operations
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
print(a | b) # Union: {1, 2, 3, 4, 5, 6}
print(a & b) # Intersection: {3, 4}
print(a - b) # Difference: {1, 2}
List Comprehensions
- Concise way to create lists.
- Can include conditions.
- More readable than traditional loops.
# Basic comprehension
squares = [x**2 for x in range(10)]
print(squares) # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
# With condition
evens = [x for x in range(20) if x % 2 == 0]
print(evens) # [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
# Transform strings
words = ["hello", "world"]
upper = [w.upper() for w in words]
print(upper) # ['HELLO', 'WORLD']