In Python, a data structure is a way of organizing and storing data so that it can be accessed and used efficiently. Python's built-in data structures are the fundamental tools you'll use to handle collections of data. The main ones are Lists, Tuples, Sets, and Dictionaries.
A key concept that separates these is mutability.
- Mutable objects (like lists, sets, and dictionaries) can be changed after they are created.
- Immutable objects (like tuples) cannot be changed once they are created.
1. list
A list is an ordered and mutable collection of items. It's one of the most versatile data structures. Think of it like a shopping list where you can add, remove, or change items.
- Key Features: Ordered, changeable, allows duplicate items, can contain different data types.
- When to Use: When you need an ordered sequence of items that you might need to modify later.
# --- 1. Lists: Ordered and Mutable ---
print("--- 1. Lists ---")
fruits_list = ["apple", "banana", "cherry", "apple"]
print(f"Original list: {fruits_list}")
# Modifying a list
fruits_list.append("orange") # Add an item to the end
fruits_list[1] = "blueberry" # Change an item
print(f"Modified list: {fruits_list}")
# Common list methods
fruits_list.sort()
print(f"Sorted list: {fruits_list}")
fruits_list.pop() # Remove the last item
print(f"List after pop: {fruits_list}")
2. tuple
A tuple is an ordered and immutable collection of items. Because it cannot be changed, it's slightly more memory-efficient and faster than a list.
- Key Features: Ordered, unchangeable, allows duplicate items.
- When to Use: For data that should not be modified, such as coordinates, configuration settings, or records that should remain constant.
# --- 2. Tuples: Ordered and Immutable ---
print("\n--- 2. Tuples ---")
coordinates = (10.0, 20.0, 30.0)
print(f"Original tuple: {coordinates}")
# Accessing items (indexing and slicing)
print(f"First item: {coordinates[0]}")
print(f"Slice: {coordinates[1:]}")
# Tuples cannot be changed. The following line would cause an error:
# coordinates[0] = 5.0
# Tuple methods are limited because they are immutable
print(f"Count of 10.0: {coordinates.count(10.0)}")
3. set
A set is an unordered and mutable collection of unique items. It automatically removes any duplicate values you try to add. Sets are highly optimized for mathematical set operations.
- Key Features: Unordered, changeable, no duplicate items.
- When to Use: When you need to store a collection of unique items and perform membership testing or mathematical set operations like union, intersection, and difference.
# --- 3. Sets: Unordered and Unique ---
print("\n--- 3. Sets ---")
unique_fruits = {"apple", "banana", "cherry", "apple"} # Duplicate "apple" is removed
print(f"Original set: {unique_fruits}")
# Adding and removing items
unique_fruits.add("orange")
unique_fruits.remove("banana")
print(f"Modified set: {unique_fruits}")
# Set operations are a key feature
set_a = {1, 2, 3, 4}
set_b = {3, 4, 5, 6}
print(f"Union of {set_a} and {set_b}: {set_a | set_b}")
print(f"Intersection: {set_a & set_b}")
4. dict (Dictionary)
A dictionary is a collection of key-value pairs. It is ordered (as of Python 3.7) and mutable. Each unique key maps to a value, making it perfect for storing related data.
- Key Features: Ordered, changeable, unique keys, stores data as key-value pairs.
- When to Use: When you need to associate data with specific labels, like storing a user's properties (name, age, email) or looking up a word's definition.
# --- 4. Dictionaries: Key-Value Pairs ---
print("\n--- 4. Dictionaries ---")
person = {
"name": "Neha",
"age": 29,
"city": "Mumbai"
}
print(f"Original dictionary: {person}")
# Accessing and modifying items
print(f"Person's name: {person['name']}")
person["email"] = "Neha@example.com" # Add a new key-value pair
person["age"] = 30 # Update a value
print(f"Modified dictionary: {person}")
# Common dictionary methods
print(f"Keys: {person.keys()}")
print(f"Values: {person.values()}")
# Looping through a dictionary
print("Looping through items:")
for key, value in person.items():
print(f" {key}: {value}")