Organizing data with lists, tuples, dicts, and sets
fruits = ["apple", "banana", "cherry"]
print(fruits[0]) # "apple" (first item)
print(fruits[-1]) # "cherry" (last item)
fruits.append("mango") # Add to end
fruits[1] = "blueberry" # Replace item at index 1
print(fruits) # ['apple', 'blueberry', 'cherry', 'mango']
print(len(fruits)) # 4list_b = list_a does NOT copy the list — both names point to the same data. Change one, both change. To copy: list_b = list_a.copy() or list_b = list_a[:].coordinates = (10, 20)
x, y = coordinates # Tuple unpacking
print(f"x={x}, y={y}")
# Can't do: coordinates[0] = 99 → TypeError!user = {
"name": "Ada",
"age": 28,
"language": "Python"
}
print(user["name"]) # "Ada"
print(user.get("email", "N/A")) # "N/A" (no crash if missing)
user["level"] = "intermediate" # Add new key
for key, value in user.items():
print(f" {key}: {value}")numbers = {1, 2, 3, 2, 1}
print(numbers) # {1, 2, 3} — duplicates removed
print(3 in numbers) # True (fast lookup)
print(99 in numbers) # False# Instead of:
squares = []
for x in range(1, 6):
squares.append(x ** 2)
# You can write:
squares = [x ** 2 for x in range(1, 6)]
print(squares) # [1, 4, 9, 16, 25]
# With a filter:
evens = [x for x in range(10) if x % 2 == 0]
print(evens) # [0, 2, 4, 6, 8]Create a dictionary of 3 students and their scores. Loop through it and print each name and score. Then use a list comprehension to create a list of names who scored 90 or above.
loading editor...
Ask about Lists & Collections
◇
Hey! I'm your AI tutor.
Ask me anything about this lesson, or paste code you're stuck on.
AI tutor is a premium feature