Python Topic
Python Data Structures – Lists, tuples, sets, dictionaries, and basic operations
1. Lists
Purpose: Ordered, mutable (changeable) collections that allow duplicate elements.
Syntax: [] or list()
Basic Operations:
python
# Creating lists
fruits = ["apple", "banana", "cherry"]
numbers = [1, 2, 3, 4, 5]
mixed = [1, "hello", 3.14, True]
# Accessing elements (zero-indexed)
print(fruits[0]) # "apple" - first element
print(fruits[-1]) # "cherry" - last element
# Slicing
print(numbers[1:4]) # [2, 3, 4] - elements from index 1 to 3
print(numbers[:3]) # [1, 2, 3] - first three elements
print(numbers[2:]) # [3, 4, 5] - from index 2 to end
Common List Methods:
python
fruits = ["apple", "banana"]
# Adding elements
fruits.append("orange") # Add to end: ["apple", "banana", "orange"]
fruits.insert(1, "grape") # Insert at position: ["apple", "grape", "banana", "orange"]
fruits.extend(["kiwi", "mango"]) # Add multiple: ["apple", "grape", "banana", "orange", "kiwi", "mango"]
# Removing elements
fruits.remove("banana") # Remove specific element
popped = fruits.pop() # Remove and return last element ("mango")
popped = fruits.pop(1) # Remove and return element at index 1 ("grape")
# Other operations
fruits.sort() # Sort alphabetically
fruits.reverse() # Reverse the list
print(fruits.count("apple")) # Count occurrences: 1
print(len(fruits)) # Get length: 3
List Comprehensions (Powerful Feature!):
python
# Create a new list by applying operation to each element
squares = [x**2 for x in range(5)] # [0, 1, 4, 9, 16]
# With condition
even_squares = [x**2 for x in range(10) if x % 2 == 0] # [0, 4, 16, 36, 64]
2. Tuples
Purpose: Ordered, immutable (unchangeable) collections. Faster than lists and used for data that shouldn't be modified.
Syntax: () or tuple()
Basic Operations:
python
# Creating tuples
colors = ("red", "green", "blue")
single_element = (42,) # Note the comma! (42) would be just an integer
coordinates = (10, 20)
# Accessing (same as lists)
print(colors[1]) # "green"
print(colors[-1]) # "blue"
# Tuples are immutable - these would cause ERRORS:
# colors[0] = "yellow" # TypeError!
# colors.append("black") # AttributeError!
# Unpacking
x, y = coordinates # x = 10, y = 20
When to Use Tuples:
-
Return multiple values from functions
-
Dictionary keys (since they're immutable)
-
Data that shouldn't change (like coordinates, configurations)
python
def get_user_info():
return "Alice", 25, "alice@email.com" # Returns a tuple
name, age, email = get_user_info() # Unpacking the tuple
3. Sets
Purpose: Unordered collections of unique elements. Fast membership testing.
Syntax: {} or set()
Basic Operations:
python
# Creating sets
unique_numbers = {1, 2, 3, 3, 2, 1} # Duplicates are removed: {1, 2, 3}
empty_set = set() # {} creates an empty dictionary, not set!
# Adding elements
unique_numbers.add(4) # {1, 2, 3, 4}
unique_numbers.add(2) # No change - 2 already exists
# Removing elements
unique_numbers.remove(3) # {1, 2, 4}
unique_numbers.discard(5) # No error if element doesn't exist
# Set operations
set_a = {1, 2, 3}
set_b = {2, 3, 4}
print(set_a | set_b) # Union: {1, 2, 3, 4}
print(set_a & set_b) # Intersection: {2, 3}
print(set_a - set_b) # Difference: {1}
print(set_a ^ set_b) # Symmetric difference: {1, 4}
Use Cases:
-
Removing duplicates from a list
-
Membership testing (very fast!)
-
Mathematical set operations
python
# Remove duplicates from list
numbers = [1, 2, 2, 3, 3, 3, 4]
unique = list(set(numbers)) # [1, 2, 3, 4]
# Fast membership testing
if "apple" in {"apple", "banana", "cherry"}:
print("Found!") # Very fast even with large sets
4. Dictionaries
Purpose: Unordered collections of key-value pairs. Like a real dictionary where you look up values using keys.
Syntax: {} or dict()
Basic Operations:
python
# Creating dictionaries
student = {
"name": "Alice",
"age": 20,
"grades": [85, 92, 78]
}
# Accessing values
print(student["name"]) # "Alice"
print(student.get("age")) # 20
print(student.get("phone", "Not provided")) # "Not provided" (default value)
# Adding/updating
student["email"] = "alice@school.com" # Add new key-value
student["age"] = 21 # Update existing value
# Removing
email = student.pop("email") # Remove and return value
del student["grades"] # Remove key-value pair
Common Dictionary Methods:
python
person = {"name": "Bob", "age": 30, "city": "New York"}
# Get all keys, values, or items
print(person.keys()) # dict_keys(['name', 'age', 'city'])
print(person.values()) # dict_values(['Bob', 30, 'New York'])
print(person.items()) # dict_items([('name', 'Bob'), ('age', 30), ('city', 'New York')])
# Iterating
for key in person:
print(f"{key}: {person[key]}")
for key, value in person.items():
print(f"{key}: {value}")
# Dictionary comprehensions
squares = {x: x**2 for x in range(5)} # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
5. Comparison Table
| Feature | List | Tuple | Set | Dictionary |
|---|---|---|---|---|
| Ordered | Yes | Yes | No | No (Python 3.7+: insertion order preserved) |
| Mutable | Yes | No | Yes | Yes |
| Allows Duplicates | Yes | Yes | No | No (keys must be unique) |
| Indexed | Yes | Yes | No | Yes (by key) |
| Use Case | General purpose | Fixed data | Unique items | Key-value pairs |
6. Putting It All Together: Practical Examples
Example 1: Student Grade Management
python
# Using multiple data structures together
students = {
"Alice": {"age": 20, "grades": [85, 92, 78], "subjects": {"Math", "Physics"}},
"Bob": {"age": 22, "grades": [76, 88, 91], "subjects": {"Chemistry", "Biology"}},
"Charlie": {"age": 21, "grades": [90, 85, 87], "subjects": {"Math", "Computer Science"}}
}
# Calculate average grade for each student
for name, info in students.items():
grades = info["grades"]
average = sum(grades) / len(grades)
print(f"{name}: {average:.1f} average")
# Find all unique subjects
all_subjects = set()
for info in students.values():
all_subjects.update(info["subjects"])
print(f"All subjects: {all_subjects}")
Example 2: Inventory System
python
# Dictionary of lists for inventory management
inventory = {
"electronics": ["laptop", "phone", "tablet"],
"books": ["novel", "textbook", "magazine"],
"clothing": ["shirt", "pants", "jacket"]
}
# Add new item to category
def add_item(category, item):
if category in inventory:
inventory[category].append(item)
else:
inventory[category] = [item]
add_item("electronics", "headphones")
add_item("food", "apple") # Creates new category
# Convert to tuple for read-only access
read_only_inventory = {category: tuple(items) for category, items in inventory.items()}
Example 3: Data Analysis Helper
python
def analyze_data(data_list):
"""Analyze a list of numbers using different data structures."""
if not data_list:
return None
# Convert to set to find unique values
unique_values = set(data_list)
# Use dictionary to count frequencies
frequency = {}
for num in data_list:
frequency[num] = frequency.get(num, 0) + 1
# Use tuple for immutable summary
summary = (
min(data_list),
max(data_list),
sum(data_list) / len(data_list),
len(unique_values)
)
return {
"unique_count": len(unique_values),
"frequency": frequency,
"summary": summary # (min, max, average, unique_count)
}
# Test the function
numbers = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
result = analyze_data(numbers)
print(f"Unique values: {result['unique_count']}")
print(f"Frequency: {result['frequency']}")
print(f"Summary: min={result['summary'][0]}, max={result['summary'][1]}, avg={result['summary'][2]:.1f}")
Short Takeaways:
-
Lists: Your go-to for ordered, modifiable collections
-
Tuples: Use for fixed data that shouldn't change
-
Sets: Perfect for unique items and fast lookups
-
Dictionaries: Ideal for key-value relationships
Comments (0)
No comments yet. Be the first to comment!