Python Programming
Python Data Types
Python Data Types
Section titled “Python Data Types”In this lesson, we’ll explore Python’s collection data types that help you organize and store multiple values.
Lists are ordered, mutable collections that can hold items of different types.
# Creating listsfruits = ["apple", "banana", "cherry"]numbers = [1, 2, 3, 4, 5]mixed = [1, "hello", 3.14, True]empty_list = []
# Accessing elements (0-indexed)print(fruits[0]) # "apple"print(fruits[-1]) # "cherry" (last item)print(fruits[1:3]) # ["banana", "cherry"] (slicing)
# Modifying listsfruits[0] = "mango" # Change elementfruits.append("orange") # Add to endfruits.insert(1, "grape") # Insert at positionfruits.remove("banana") # Remove by valuepopped = fruits.pop() # Remove and return lastdel fruits[0] # Delete by index
# List operationsnumbers = [3, 1, 4, 1, 5]numbers.sort() # Sort in place: [1, 1, 3, 4, 5]numbers.reverse() # Reverse in place: [5, 4, 3, 1, 1]print(len(numbers)) # Length: 5print(sum(numbers)) # Sum: 14print(min(numbers)) # Minimum: 1print(max(numbers)) # Maximum: 5
# List comprehensionsquares = [x**2 for x in range(5)] # [0, 1, 4, 9, 16]evens = [x for x in range(10) if x % 2 == 0] # [0, 2, 4, 6, 8]Tuples are ordered, immutable collections - once created, they cannot be modified.
# Creating tuplescoordinates = (10, 20)rgb = (255, 128, 0)single = (42,) # Note the comma for single-element tuple
# Accessing elementsprint(coordinates[0]) # 10x, y = coordinates # Tuple unpacking
# Tuples are immutable# coordinates[0] = 5 # Error! Cannot modify
# When to use tuples# - For data that shouldn't change (coordinates, RGB values)# - As dictionary keys# - For function return valuesdef get_user(): return ("Alice", 25, "alice@email.com")
name, age, email = get_user()Dictionaries
Section titled “Dictionaries”Dictionaries store key-value pairs for fast lookups.
# Creating dictionariesperson = { "name": "Alice", "age": 25, "city": "New York"}
# Accessing valuesprint(person["name"]) # "Alice"print(person.get("age")) # 25print(person.get("country", "Unknown")) # "Unknown" (default)
# Modifying dictionariesperson["email"] = "alice@email.com" # Add new keyperson["age"] = 26 # Update existingdel person["city"] # Delete keyperson.pop("email") # Remove and return
# Dictionary methodsprint(person.keys()) # dict_keys(['name', 'age'])print(person.values()) # dict_values(['Alice', 26])print(person.items()) # dict_items([('name', 'Alice'), ('age', 26)])
# Iterating over dictionariesfor key in person: print(f"{key}: {person[key]}")
for key, value in person.items(): print(f"{key}: {value}")
# Dictionary comprehensionsquares = {x: x**2 for x in range(5)}# {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}Sets are unordered collections of unique elements.
# Creating setsfruits = {"apple", "banana", "cherry"}numbers = {1, 2, 3, 3, 3} # Duplicates removed: {1, 2, 3}empty_set = set() # Note: {} creates empty dict, not set
# Set operationsfruits.add("orange")fruits.remove("banana") # Raises error if not foundfruits.discard("mango") # No error if not found
# Set mathematicsa = {1, 2, 3, 4}b = {3, 4, 5, 6}
print(a | b) # Union: {1, 2, 3, 4, 5, 6}print(a & b) # Intersection: {3, 4}print(a - b) # Difference: {1, 2}print(a ^ b) # Symmetric difference: {1, 2, 5, 6}
# Membership testing (very fast)print(3 in a) # TrueComparison Summary
Section titled “Comparison Summary”| Feature | List | Tuple | Dictionary | Set |
|---|---|---|---|---|
| Ordered | ✅ | ✅ | ✅* | ❌ |
| Mutable | ✅ | ❌ | ✅ | ✅ |
| Duplicates | ✅ | ✅ | Keys: ❌ | ❌ |
| Indexing | ✅ | ✅ | By key | ❌ |
| Syntax | [] | () | {} | {} |
*Dictionaries maintain insertion order since Python 3.7
Practice Exercises
Section titled “Practice Exercises”Exercise 1: List Manipulation
Section titled “Exercise 1: List Manipulation”Remove duplicates from a list while preserving order.
numbers = [1, 3, 2, 3, 1, 4, 2, 5]# Expected: [1, 3, 2, 4, 5]Exercise 2: Word Counter
Section titled “Exercise 2: Word Counter”Count the frequency of each word in a sentence.
sentence = "the quick brown fox jumps over the lazy dog"# Expected: {"the": 2, "quick": 1, ...}