Data structures are how Python stores and organizes data. In this lesson, you’ll learn the most-used built-ins: lists, tuples, sets, and dictionaries—plus powerful comprehensions for building them quickly.
1) Lists
A list is an ordered, mutable collection (you can change it). Use square brackets [].
a) Creating & Indexing
fruits = ["apple", "banana", "mango"]
print(fruits[0]) # apple (0-based index)
print(fruits[-1]) # mango (last item)
b) Slicing
Use [start:stop:step]. stop is exclusive.
nums = [0, 1, 2, 3, 4, 5, 6]
print(nums[2:5]) # [2, 3, 4]
print(nums[:3]) # [0, 1, 2]
print(nums[::2]) # [0, 2, 4, 6]
print(nums[::-1]) # reversed copy
c) Common Methods
items = [3, 1, 4]
items.append(2) # [3, 1, 4, 2]
items.extend([9, 7]) # [3, 1, 4, 2, 9, 7]
items.insert(1, 99) # insert at index 1
items.remove(4) # remove first 4
last = items.pop() # pop last item (7)
items.clear() # []
Sorting
nums = [5, 2, 9, 1]
nums.sort() # in-place ascending → [1, 2, 5, 9]
nums.sort(reverse=True) # in-place descending
# or non-destructive:
sorted_nums = sorted([5, 2, 9, 1]) # returns a new list
Copy vs Reference
a = [1, 2, 3]
b = a # reference (same list)
c = a.copy() # shallow copy (new list)
a.append(4)
print(b) # [1, 2, 3, 4] (changed)
print(c) # [1, 2, 3] (unchanged)
d) List Comprehensions
Build lists from loops/conditions in one line.
nums = [1, 2, 3, 4, 5]
squares = [n * n for n in nums] # [1, 4, 9, 16, 25]
evens = [n for n in nums if n % 2 == 0] # [2, 4]
pairs = [(a, b) for a in [1, 2] for b in ["A", "B"]] # [(1,'A'), (1,'B'), (2,'A'), (2,'B')]
2) Tuples
A tuple is like a list but immutable (cannot change). Use parentheses ().
point = (10, 20)
print(point[0]) # 10
# point[0] = 99 # ❌ TypeError (immutable)
# Packing & Unpacking
person = ("Ali", 31, "Pakistan")
name, age, country = person
print(name, age, country)
Single-item tuple: don’t forget the trailing comma: (42,)
3) Sets
A set is an unordered collection of unique elements. Great for membership tests and removing duplicates.
unique = {1, 2, 2, 3}
print(unique) # {1, 2, 3}
unique.add(5)
unique.discard(2) # remove if present; no error if missing
print(3 in unique) # True
Set Operations
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}
print(a ^ b) # symmetric difference → {1, 2, 4, 5}
Note: Sets are unordered (no stable index) and require hashable elements (e.g., numbers, strings, tuples; not lists/dicts).
Set Comprehension
nums = [1, 2, 2, 3, 4, 4]
unique_squares = {n * n for n in nums} # {16, 1, 4, 9}
4) Dictionaries
A dict maps keys to values. Keys must be hashable and unique. In modern Python, dicts preserve insertion order.
user = {"id": 1, "name": "Ammar"}
print(user["name"]) # Ammar
user["email"] = "[email protected]" # add
user["name"] = "Ali" # update
print("id" in user) # True (membership checks keys)
# Safe get with default
print(user.get("role", "guest")) # "guest"
# Remove
user.pop("email", None) # remove if exists
# del user["email"] # KeyError if absent
Iterating
for key in user.keys():
print(key)
for value in user.values():
print(value)
for key, value in user.items():
print(key, "→", value)
Nested Dictionaries
profile = {
"name": "Ali",
"address": {"city": "Islamabad", "zip": "44000"},
"skills": ["Python", "SQL"]
}
print(profile["address"]["city"]) # Islamabad
Dict Comprehension
names = ["ali", "ammar", "sara"]
lengths = {name: len(name) for name in names} # {"ali": 3, "ammar": 5, "sara": 4}
# Filter + transform
prices = {"apple": 100, "banana": 40, "mango": 120}
discounted = {k: v * 0.9 for k, v in prices.items() if v >= 100}
# {"apple": 90.0, "mango": 108.0}
5) When to Use What?
- List: ordered, allows duplicates, you’ll modify it.
- Tuple: ordered, fixed data that shouldn’t change (safer as keys or struct-like records).
- Set: unique items, fast membership checks, math-like set operations.
- Dict: labeled data (key → value), configuration, lookups.
Common pitfalls:
- Lists are mutable: copying by reference can surprise you—use
.copy()for a shallow copy. - Sets & dicts need hashable keys/elements (no lists as keys, but tuples are fine).
- Sorting:
list.sort()changes the list;sorted(list)returns a new one.
Key Takeaways
- Lists: ordered & mutable; master indexing, slicing, methods, and list comprehensions.
- Tuples: immutable lists—great for fixed records and safe unpacking.
- Sets: unique items; use union/intersection/difference for fast math-like operations.
- Dictionaries: key→value mapping; iterate with
.items(), use.get()for safe reads. - Comprehensions (list/set/dict) express filters & transforms concisely—keep them readable.
Continue your learning with our in-depth guide to Python Object-Oriented Programming (OOP): classes, objects, methods, inheritance & special methods to learn how to model real-world problems using reusable, maintainable code.
Leave a comment
Your email address will not be published. Required fields are marked *
