python
examples
examples.py🐍python
"""
04 - Data Structures: Examples
Run this file to see lists, tuples, dicts, and sets in action!
"""
print("=" * 60)
print("DATA STRUCTURES - EXAMPLES")
print("=" * 60)
# =============================================================================
# 1. LISTS
# =============================================================================
print("\n--- 1. Lists ---\n")
# Creating lists
numbers = [1, 2, 3, 4, 5]
mixed = [1, "hello", 3.14, True]
empty = []
print(f"Numbers: {numbers}")
print(f"Mixed types: {mixed}")
# Accessing elements
fruits = ["apple", "banana", "cherry", "date", "elderberry"]
print(f"\nFruits list: {fruits}")
print(f"First item (fruits[0]): {fruits[0]}")
print(f"Last item (fruits[-1]): {fruits[-1]}")
print(f"Slice [1:4]: {fruits[1:4]}")
print(f"Every other [::2]: {fruits[::2]}")
# Modifying lists
print("\nModifying lists:")
fruits.append("fig")
print(f"After append('fig'): {fruits}")
fruits.insert(1, "blueberry")
print(f"After insert(1, 'blueberry'): {fruits}")
fruits.remove("cherry")
print(f"After remove('cherry'): {fruits}")
popped = fruits.pop()
print(f"After pop() returned '{popped}': {fruits}")
# List methods
numbers = [3, 1, 4, 1, 5, 9, 2, 6]
print(f"\nNumbers: {numbers}")
print(f"Length: {len(numbers)}")
print(f"Sum: {sum(numbers)}")
print(f"Min: {min(numbers)}, Max: {max(numbers)}")
print(f"Count of 1: {numbers.count(1)}")
print(f"Index of 5: {numbers.index(5)}")
numbers_sorted = sorted(numbers)
print(f"Sorted (new list): {numbers_sorted}")
numbers.sort()
print(f"Sort in place: {numbers}")
numbers.reverse()
print(f"Reversed: {numbers}")
# List comprehension
squares = [x**2 for x in range(1, 6)]
print(f"\nSquares [1-5]: {squares}")
evens = [x for x in range(10) if x % 2 == 0]
print(f"Even numbers [0-9]: {evens}")
# =============================================================================
# 2. TUPLES
# =============================================================================
print("\n--- 2. Tuples ---\n")
# Creating tuples
point = (3, 4)
single = (42,) # Note the comma!
from_values = 10, 20, 30 # Packing
print(f"Point: {point}")
print(f"Single item tuple: {single}, type: {type(single)}")
print(f"Packed tuple: {from_values}")
# Accessing elements
coords = (10, 20, 30, 40, 50)
print(f"\nCoords: {coords}")
print(f"First: {coords[0]}, Last: {coords[-1]}")
print(f"Slice [1:4]: {coords[1:4]}")
# Unpacking
x, y = point
print(f"\nUnpacking point: x={x}, y={y}")
first, *middle, last = coords
print(f"Unpacking coords: first={first}, middle={middle}, last={last}")
# Tuple methods
numbers = (1, 2, 3, 2, 4, 2, 5)
print(f"\nTuple: {numbers}")
print(f"Count of 2: {numbers.count(2)}")
print(f"Index of 3: {numbers.index(3)}")
# Tuples as dict keys
locations = {
(40.7128, -74.0060): "New York",
(34.0522, -118.2437): "Los Angeles"
}
print(f"\nLocations dict with tuple keys: {locations}")
print(f"Location at (40.7128, -74.0060): {locations[(40.7128, -74.0060)]}")
# =============================================================================
# 3. DICTIONARIES
# =============================================================================
print("\n--- 3. Dictionaries ---\n")
# Creating dicts
person = {
"name": "Alice",
"age": 25,
"city": "New York",
"hobbies": ["reading", "coding"]
}
print(f"Person: {person}")
# Accessing values
print(f"\nName: {person['name']}")
print(f"Age: {person.get('age')}")
print(f"Country (with default): {person.get('country', 'Unknown')}")
# Keys, values, items
print(f"\nKeys: {list(person.keys())}")
print(f"Values: {list(person.values())}")
# Modifying
person["email"] = "alice@email.com"
print(f"\nAfter adding email: {person}")
person["age"] = 26
print(f"After updating age: {person}")
person.update({"city": "Boston", "phone": "555-1234"})
print(f"After update(): {person}")
# Removing
del person["phone"]
print(f"After del phone: {person}")
# Iterating
print("\nIterating over dict:")
for key, value in person.items():
print(f" {key}: {value}")
# Dict comprehension
squares = {x: x**2 for x in range(1, 6)}
print(f"\nSquares dict: {squares}")
# Filtering
even_squares = {k: v for k, v in squares.items() if k % 2 == 0}
print(f"Even number squares: {even_squares}")
# =============================================================================
# 4. SETS
# =============================================================================
print("\n--- 4. Sets ---\n")
# Creating sets
numbers = {1, 2, 3, 4, 5}
from_list = set([1, 2, 2, 3, 3, 3]) # Duplicates removed
print(f"Numbers set: {numbers}")
print(f"From list with duplicates: {from_list}")
# Adding and removing
numbers.add(6)
print(f"After add(6): {numbers}")
numbers.update([7, 8, 9])
print(f"After update([7,8,9]): {numbers}")
numbers.discard(9)
print(f"After discard(9): {numbers}")
# Set operations
a = {1, 2, 3, 4, 5}
b = {4, 5, 6, 7, 8}
print(f"\nSet A: {a}")
print(f"Set B: {b}")
print(f"Union (A | B): {a | b}")
print(f"Intersection (A & B): {a & b}")
print(f"Difference (A - B): {a - b}")
print(f"Symmetric Diff (A ^ B): {a ^ b}")
# Subset/superset
print(f"\n{{1,2}} subset of {{1,2,3}}: {({1,2}).issubset({1,2,3})}")
print(f"{{1,2,3}} superset of {{1,2}}: {({1,2,3}).issuperset({1,2})}")
# Practical use: remove duplicates
my_list = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
unique = list(set(my_list))
print(f"\nOriginal list: {my_list}")
print(f"Unique items: {unique}")
# =============================================================================
# 5. NESTED STRUCTURES
# =============================================================================
print("\n--- 5. Nested Structures ---\n")
# 2D List (Matrix)
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
print("Matrix:")
for row in matrix:
print(f" {row}")
print(f"Element at [1][2]: {matrix[1][2]}")
# Nested dict
users = {
"alice": {
"age": 25,
"email": "alice@email.com",
"roles": ["admin", "user"]
},
"bob": {
"age": 30,
"email": "bob@email.com",
"roles": ["user"]
}
}
print(f"\nUsers dict:")
for username, info in users.items():
print(f" {username}: {info['email']}, roles: {info['roles']}")
# List of dicts
products = [
{"name": "Laptop", "price": 999, "stock": 50},
{"name": "Phone", "price": 699, "stock": 100},
{"name": "Tablet", "price": 499, "stock": 75}
]
print(f"\nProducts:")
for p in products:
print(f" {p['name']}: ${p['price']} ({p['stock']} in stock)")
# Sort list of dicts
by_price = sorted(products, key=lambda x: x["price"])
print(f"\nSorted by price:")
for p in by_price:
print(f" {p['name']}: ${p['price']}")
# =============================================================================
# 6. PRACTICAL EXAMPLES
# =============================================================================
print("\n--- 6. Practical Examples ---\n")
# Example 1: Word frequency counter
text = "the quick brown fox jumps over the lazy dog the fox"
words = text.split()
frequency = {}
for word in words:
frequency[word] = frequency.get(word, 0) + 1
print(f"Word frequency: {frequency}")
# Example 2: Grouping by category
items = [
("apple", "fruit"),
("carrot", "vegetable"),
("banana", "fruit"),
("broccoli", "vegetable"),
("cherry", "fruit")
]
groups = {}
for item, category in items:
if category not in groups:
groups[category] = []
groups[category].append(item)
print(f"\nGrouped items: {groups}")
# Example 3: Finding common elements
list1 = [1, 2, 3, 4, 5]
list2 = [4, 5, 6, 7, 8]
list3 = [5, 6, 7, 8, 9]
common_all = set(list1) & set(list2) & set(list3)
print(f"\nCommon in all three lists: {common_all}")
# Example 4: Inverting a dictionary
original = {"a": 1, "b": 2, "c": 3}
inverted = {v: k for k, v in original.items()}
print(f"\nOriginal: {original}")
print(f"Inverted: {inverted}")
# Example 5: Flatten nested list
nested = [[1, 2], [3, 4, 5], [6], [7, 8, 9, 10]]
flat = [item for sublist in nested for item in sublist]
print(f"\nNested: {nested}")
print(f"Flattened: {flat}")
print("\n" + "=" * 60)
print("END OF EXAMPLES")
print("=" * 60)