Objective:
Handle and manipulate data efficiently using Python’s built-in data structures, enabling you to write clean and optimized programs.
Topics and Examples:
1. Lists: Creation, Indexing, Slicing, Methods
Lists are ordered, mutable collections of items.
Example:
# Creation
fruits = ["apple", "banana", "cherry"]
# Indexing
print(fruits[0]) # apple
print(fruits[-1]) # cherry
# Slicing
print(fruits[0:2]) # ['apple', 'banana']
# Methods
fruits.append("orange") # Add item
fruits.pop() # Remove last item
fruits.extend(["mango", "grape"]) # Add multiple items
print(fruits)
2. Tuples: Immutability and Unpacking
Tuples are ordered, immutable collections.
Example:
# Creation
coordinates = (10, 20)
# Access
print(coordinates[0]) # 10
# Unpacking
x, y = coordinates
print(x, y) # 10 20
# Tuples are immutable
# coordinates[0] = 5 # This will raise an error
3. Sets: Unique Elements and Set Operations
Sets are unordered collections of unique elements.
Example:
# Creation
colors = {"red", "green", "blue", "red"} # duplicates removed
print(colors) # {'red', 'green', 'blue'}
# Set operations
a = {1, 2, 3}
b = {3, 4, 5}
print(a.union(b)) # {1, 2, 3, 4, 5}
print(a.intersection(b))# {3}
print(a.difference(b)) # {1, 2}
4. Dictionaries: Key-Value Pairs
Dictionaries store data as key-value pairs and are mutable.
Example:
# Creation
person = {"name": "Chinmaya", "age": 25, "city": "Bhubaneswar"}
# Access
print(person["name"]) # Chinmaya
# Methods
print(person.get("age")) # 25
print(person.keys()) # dict_keys(['name', 'age', 'city'])
print(person.values()) # dict_values(['Chinmaya', 25, 'Bhubaneswar'])
print(person.items()) # dict_items([('name', 'Chinmaya'), ('age', 25), ('city', 'Bhubaneswar')])
5. Strings: Indexing, Slicing, Formatting, and Methods
Strings are sequences of characters and immutable.
Example:
text = "Hello, Python"
# Indexing & Slicing
print(text[0]) # H
print(text[0:5]) # Hello
print(text[-6:]) # Python
# Formatting
name = "Chinmaya"
age = 25
print(f"My name is {name} and I am {age} years old.") # f-string formatting
# String methods
print(text.upper()) # HELLO, PYTHON
print(text.lower()) # hello, python
print(text.replace("Python", "World")) # Hello, World
print(text.split(",")) # ['Hello', ' Python']
6. Advanced: Nested Data Structures
Python allows nesting of lists, tuples, dictionaries, and sets.
Example:
# List of dictionaries
students = [
{"name": "Chinmaya", "age": 25},
{"name": "Rout", "age": 26}
]
print(students[0]["name"]) # Chinmaya
# Dictionary with list values
person = {"name": "Chinmaya", "hobbies": ["reading", "coding"]}
print(person["hobbies"][1]) # coding
# Nested lists
matrix = [[1, 2], [3, 4]]
print(matrix[1][0]) # 3
This section covers all essential Python data structures, their properties, methods, and practical examples for beginners and intermediate learners.