🐍 Python
Data Structures
Python has four built-in data structures: Lists, Dictionaries, Tuples, and Sets. Each serves a different purpose and has unique properties.
Lists and dictionaries
Editor
Python
Output
Try it
Add new items to the list and dictionary. Try slicing with different start and end values.
Lists — in depth
# Creating lists
numbers = [1, 2, 3, 4, 5]
mixed = [1, "hello", 3.14, True]
# Common list methods
numbers.append(6) # Add to end
numbers.insert(0, 0) # Insert at index
numbers.remove(3) # Remove first occurrence
popped = numbers.pop() # Remove and return last
numbers.sort() # Sort in place
length = len(numbers) # Get length
# Slicing
nums = [0, 1, 2, 3, 4, 5]
nums[1:4] # [1, 2, 3]
nums[:3] # [0, 1, 2]
nums[2:] # [2, 3, 4, 5]
nums[-1] # 5
Dictionaries — in depth
# Creating dictionaries
scores = {"Alice": 95, "Bob": 87, "Charlie": 92}
# Access and modify
scores["Dave"] = 88 # Add new key
del scores["Bob"] # Delete a key
alice_score = scores.get("Alice", 0) # Safe access
# Useful methods
scores.keys() # dict_keys(['Alice', 'Charlie', 'Dave'])
scores.values() # dict_values([95, 92, 88])
scores.items() # dict_items([('Alice', 95), ...])
Tuples and sets
# Tuples — ordered, immutable
coordinates = (10, 20)
print(coordinates[0]) # 10
# coordinates[0] = 5 # Error! Tuples can't change
# Sets — unordered, unique values
colors = {"red", "blue", "green", "red"}
print(colors) # {'red', 'blue', 'green'}
colors.add("yellow")
colors.remove("blue")
# Set operations
a = {1, 2, 3}
b = {2, 3, 4}
print(a & b) # {2, 3} — intersection
print(a | b) # {1, 2, 3, 4} — union
List comprehensions
A concise way to create lists from existing data:
# Traditional way
squares = []
for x in range(5):
squares.append(x ** 2)
# List comprehension
squares = [x ** 2 for x in range(5)] # [0, 1, 4, 9, 16]
# With a condition
evens = [x for x in range(10) if x % 2 == 0] # [0, 2, 4, 6, 8]
Quiz
Which data structure uses key-value pairs?
Challenge
Create a dictionary of 3 items (e.g., a small phonebook). Then loop through its keys and values using .items() and print each one.