🐍 Python Tutorial: Data Structures
Python provides powerful built-in data structures that allow you to store, access, and manipulate collections of data efficiently. The most commonly used are lists, tuples, dictionaries, and sets.
1. Lists
Lists are ordered, mutable collections of items. They can store any data type and even a mix of types. Lists are ideal when you need to maintain the order of items and allow changes.
fruits = ["apple", "banana", "cherry"]
print(fruits[1]) # banana
fruits.append("orange")
print(fruits) # ['apple', 'banana', 'cherry', 'orange']
fruits[0] = "grape" # Modify element
print(fruits)
fruits.remove("banana") # Remove element
print(fruits)2. Tuples
Tuples are ordered and immutable collections. Once created, their contents can't be changed. They are often used for fixed data, like coordinates or RGB values.
coordinates = (10, 20)
print(coordinates[0])
# coordinates[0] = 15 # This would raise an error3. Dictionaries
Dictionaries are collections of key-value pairs. Keys must be unique and are used to access their corresponding values. They are very useful for structured data.
person = {"name": "Alice", "age": 30}
print(person["name"])
person["city"] = "New York" # Add new key-value pair
print(person)
person["age"] = 31 # Modify existing value
del person["city"] # Delete a key-value pair
print(person)4. Sets
Sets are unordered collections of unique elements. They are great for removing duplicates and performing set operations like union, intersection, and difference.
unique_numbers = {1, 2, 3, 2, 1}
print(unique_numbers) # {1, 2, 3}
unique_numbers.add(4)
print(unique_numbers)
unique_numbers.discard(2)
print(unique_numbers)5. Common Operations
Each data structure comes with helpful built-in functions and methods to manipulate and query data. Here are some examples:
# List operations
nums = [4, 2, 7, 1]
nums.sort()
print(nums) # [1, 2, 4, 7]
nums.reverse()
print(nums) # [7, 4, 2, 1]
# Dictionary operations
person = {"name": "Bob", "age": 25}
print(person.get("age")) # 25
print(person.keys()) # dict_keys(['name', 'age'])
print(person.values()) # dict_values(['Bob', 25])
# Set operations
set1 = {1, 2, 3}
set2 = {3, 4, 5}
print(set1.union(set2)) # {1, 2, 3, 4, 5}
print(set1.intersection(set2)) # {3}