Python Lists and Dictionaries
Introduction
Lists and dictionaries are two of Python's most used data structures. Mastering them is essential for writing effective Python code.
Lists
A list is an ordered collection of items.
fruits = ["apple", "banana", "cherry"]
print(fruits[0]) # apple
Common List Operations
You can add, remove, and loop over items easily.
fruits.append("mango")
fruits.remove("banana")
for fruit in fruits:
print(fruit)
List Comprehensions
A concise way to create lists.
squares = [x * x for x in range(10)]
Dictionaries
A dictionary stores key-value pairs.
person = {
"name": "Alice",
"age": 25,
"city": "New York"
}
print(person["name"]) # Alice
Looping Over Dictionaries
Use .items() to get both key and value.
for key, value in person.items():
print(key, ":", value)
Nested Structures
You can combine lists and dictionaries for complex data.
users = [
{"name": "Alice", "age": 25},
{"name": "Bob", "age": 30}
]