What You’ll Learn:
Data structures help you organize and store data efficiently so that operations like insertion, deletion, searching, and sorting become easier.
Python has four main built-in data structures:
fruits = ["apple", "banana", "cherry"]
Accessing Items:
print(fruits[0]) # Output: apple
print(fruits[-1]) # Output: cherry (last item)
# Add
fruits.append("kiwi")
# Insert at position
fruits.insert(1, "grape")
# Delete
fruits.remove("banana") # Removes by value
del fruits[2] # Rmmoves by index
append()
, extend()
, insert()
, remove()
, pop()
, sort()
, reverse()
, count()
, index()
Modifying a List:
fruits[1] = "blueberry"
print(fruits) # ['apple', 'blueberry', 'cherry']
Method | Description |
---|---|
append() | Add element to end |
insert(index, x) | Insert at specific position |
remove(x) | Remove first occurrence of x |
pop() | Remove and return last item |
sort() | Sort list |
reverse() | Reverse the list |
numbers = [3, 1, 4]
numbers.append(2)
numbers.sort()
print(numbers) # [1, 2, 3, 4]
person = ("Akash", 25, "India")
Accessing Elements:
print(person[0]) # Akash
Use tuples when data shouldn’t change (e.g., coordinates, constants).
Creating a Set:
colors = {"red", "green", "blue"}
Set Operations:
colors.add("yellow")
colors.remove("green")
Set Math:
a = {1, 2, 3}
b = {3, 4, 5}
print(a | b) # Union → {1, 2, 3, 4, 5}
print(a & b) # Intersection → {3}
print(a - b) # Difference → {1, 2}
Great for checking membership, uniqueness, and eliminating duplicates.
Creating a Dictionary:
student = {
"name": "Akash",
"age": 25,
"course": "Python"
}
Accessing & Modifying:
print(student["name"]) # Akash
student["age"] = 26 # Update
student["email"] = "a@x.com" # Add new key
Method | Description |
---|---|
keys() | All keys |
values() | All values |
items() | All key-value pairs |
get(key) | Get value by key safely |
pop(key) | Remove item by key |
Structure | Ordered | Mutable | Duplicates | Use When… |
---|---|---|---|---|
List | Yes | Yes | Yes | Order matters, frequent updates |
Tuple | Yes | No | Yes | Fixed data, safety |
Set | No | Yes | No | Uniqueness, fast membership tests |
Dictionary | Yes* | Yes | Keys unique | Map keys to values |
List Example – Shopping Cart
cart = ["apple", "banana", "apple"]
print(cart.count("apple")) # Output: 2
Tuple Example – Coordinates
location = (37.7749, -122.4194)
Set Example – Unique Voters
voters = {"alice", "bob", "alice"}
print(voters) # Output: {'alice', 'bob'}
Dictionary Example – API Response
response = {
"status": "success",
"data": {"user_id": 101, "name": "Akash"}
}
"available": True
dict[key]
vs dict.get(key)
?
Leave a Reply