Python Data Structures Guide
Understanding data structures is crucial for writing efficient Python code. Let's explore the most important ones.
Lists
Lists are ordered, mutable collections that can hold multiple items.
Creating lists
fruits = ["apple", "banana", "orange"]
numbers = [1, 2, 3, 4, 5]
mixed = [1, "hello", 3.14, True]
Accessing elements
print(fruits[0]) # "apple"
print(fruits[-1]) # "orange" (last element)
List methods
fruits.append("grape")
fruits.remove("banana")
numbers.sort()
Dictionaries
Dictionaries store key-value pairs and are perfect for mapping relationships.
Creating dictionaries
person = {
"name": "John",
"age": 30,
"city": "New York"
}
Accessing values
print(person["name"]) # "John"
Adding new keys
person["email"] = "john@example.com"
Dictionary methods
person.keys()
person.values()
person.items()
Sets
Sets are unordered collections of unique items. Perfect for membership testing and eliminating duplicates.
Creating sets
colors = {"red", "green", "blue"}
numbers = {1, 2, 2, 3, 3, 3} # {1, 2, 3}
Set operations
colors.add("yellow")
colors.remove("red")
Set operations
set_a = {1, 2, 3}
set_b = {3, 4, 5}
union = set_a | set_b # {1, 2, 3, 4, 5}
intersection = set_a & set_b # {3}
Tuples
Tuples are immutable sequences. Use them when you need to ensure data won't change.
Creating tuples
point = (10, 20)
rgb = (255, 0, 128)
Accessing elements
print(point[0]) # 10
Tuple unpacking
x, y = point
r, g, b = rgb
Choosing the Right Data Structure
Master these four data structures and you'll be able to solve most programming problems efficiently!