Core Structure
Lists, Tuples, and Dictionaries: Python’s Core Structures
Introduction
Data structures are fundamental to any programming language, and Python provides several built-in options for managing collections of data. In this post, we’ll explore lists, tuples, and dictionaries—their characteristics, use cases, and common operations.
1. Lists: Mutable and Ordered
A list is a mutable, ordered collection of items. You can store any type of data in a list, and it can even mix types.
Creating Lists
python
Copy code# Empty list
= []
my_list
# List with values
= ["apple", "banana", "cherry"] fruits
Accessing Elements
python
Copy codeprint(fruits[0]) # First element: "apple"
print(fruits[-1]) # Last element: "cherry"
Common List Operations
python
Copy code"orange") # Add an element
fruits.append("banana") # Remove an element
fruits.remove(1] = "grape" # Modify an element
fruits[print(len(fruits)) # Get the length
Iterating Over a List
python
Copy codefor fruit in fruits:
print(fruit)
When to Use Lists
- Storing a collection of items where order matters.
- When you need to frequently modify the collection.
2. Tuples: Immutable and Ordered
A tuple is similar to a list but immutable, meaning you cannot change its contents once created.
Creating Tuples
python
Copy code# Empty tuple
= ()
my_tuple
# Tuple with values
= (10, 20)
coordinates
# Single-element tuple (note the comma)
= (5,) single
Accessing Elements
python
Copy codeprint(coordinates[0]) # First element: 10
Key Features
- Tuples are faster than lists.
- Commonly used for fixed collections of items (e.g., coordinates, settings).
When to Use Tuples
Data integrity: Use tuples to ensure data cannot be modified.
Returning multiple values from a function:
python Copy codedef get_point(): return (10, 20) = get_point() x, y
3. Dictionaries: Key-Value Pairs
A dictionary is an unordered collection of key-value pairs, where each key maps to a value.
Creating Dictionaries
python
Copy code# Empty dictionary
= {}
my_dict
# Dictionary with values
= {"name": "Alice", "age": 30, "city": "New York"} person
Accessing and Modifying Data
python
Copy code# Access value by key
print(person["name"]) # Output: "Alice"
# Add or modify key-value pairs
"job"] = "Engineer"
person["age"] = 31
person[
# Remove a key-value pair
del person["city"]
Common Dictionary Operations
python
Copy code# Check if a key exists
print("name" in person) # Output: True
# Iterate through keys
for key in person:
print(key)
# Iterate through key-value pairs
for key, value in person.items():
print(f"{key}: {value}")
When to Use Dictionaries
- Representing data with named attributes.
- Fast lookups by key (e.g., a phone book or settings).
4. Comparison: Lists vs. Tuples vs. Dictionaries
Feature | List | Tuple | Dictionary |
---|---|---|---|
Mutable | Yes | No | Yes |
Ordered | Yes | Yes | No (insertion order since Python 3.7) |
Use Case | General-purpose | Fixed collections | Key-value mappings |
5. Practical Example
Problem: Managing a Shopping List
Let’s combine lists and dictionaries to solve a real-world problem.
Code Example:
python
Copy code# Shopping list with item names and quantities
= [
shopping_list "item": "apple", "quantity": 5},
{"item": "banana", "quantity": 3},
{"item": "milk", "quantity": 1}
{
]
# Add a new item
"item": "bread", "quantity": 2})
shopping_list.append({
# Update quantity
for item in shopping_list:
if item["item"] == "milk":
"quantity"] += 1
item[
# Print the shopping list
for item in shopping_list:
print(f"{item['item']}: {item['quantity']}")
Conclusion
Lists, tuples, and dictionaries are versatile tools in Python for organizing and working with data. By mastering these core data structures, you’ll be prepared to tackle more complex tasks and advanced structures.