🔰 Introduction: What Are Collections in Programming?
In programming, collections are containers used to store, organize, and manipulate groups of related data. Think of them as digital boxes or shelves where you can group similar or different items.
In Python, collections are fundamental because they allow you to:
- Work with groups of data (like names, scores, or items in a game).
- Process multiple values efficiently using loops and functions.
- Organize data in ways that make it easy to access, modify, and understand.
Python includes several built-in collection types, each suited to different tasks. This guide focuses on the four most commonly used:
📚 Overview of Python’s Main Collection Types
| Collection | Description | Mutable? | Ordered? | Duplicates Allowed? | Example Use Case |
|---|---|---|---|---|---|
list | Ordered sequence of items | ✅ Yes | ✅ Yes | ✅ Yes | A to-do list |
tuple | Ordered, fixed-size sequence | ❌ No | ✅ Yes | ✅ Yes | GPS coordinates |
set | Unordered collection of unique items | ✅ Yes | ❌ No | ❌ No | Tags or categories |
dict | Collection of key-value pairs | ✅ Yes | ✅ (3.7+) | ✅ (keys must be unique) | Storing user profiles |
Now, let’s dive deep into lists, Python’s most flexible and commonly used collection type.
🧾 Lists in Python
🔹 What Is a List?
A list is an ordered, changeable collection of items. It can hold anything: numbers, strings, even other lists.
🔹 Creating Lists
“`python
Empty list
my_list = []
List with elements
fruits = [“apple”, “banana”, “cherry”]
List with mixed data types
info = [“John”, 25, True]
🔹 Indexing and Slicing
Python lists are zero-indexed: the first item is at position 0.
Use slicing to get parts of a list.
python
Copy
Edit
fruits = [“apple”, “banana”, “cherry”, “date”]
print(fruits[0]) # “apple”
print(fruits[-1]) # “date” (last item)
print(fruits[1:3]) # [“banana”, “cherry”] (from index 1 up to, not including, 3)
🔹 Common List Methods
Method Description
append(x) Adds x to the end
insert(i, x) Inserts x at position i
remove(x) Removes first occurrence of x
pop(i) Removes and returns item at index i (or last if not specified)
sort() Sorts the list (in-place)
reverse() Reverses the list order
clear() Removes all items
python
Copy
Edit
numbers = [3, 1, 4]
numbers.append(2) # [3, 1, 4, 2]
numbers.insert(1, 10) # [3, 10, 1, 4, 2]
numbers.remove(1) # [3, 10, 4, 2]
popped = numbers.pop() # returns 2, list becomes [3, 10, 4]
numbers.sort() # [3, 4, 10]
🔹 Iterating Over Lists
python
Copy
Edit
Simple for-loop
for fruit in fruits:
print(fruit)
Using enumerate to get index and value
for index, fruit in enumerate(fruits):
print(f”{index}: {fruit}”)
🔹 List Comprehensions
A concise way to create new lists.
python
Copy
Edit
Create a list of squares
squares = [x**2 for x in range(5)] # [0, 1, 4, 9, 16]
Filter a list
evens = [x for x in range(10) if x % 2 == 0]
🔹 Nested Lists
Lists inside lists allow matrix-like structures.
python
Copy
Edit
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
Accessing an element
print(matrix[1][2]) # 6
🔹 Performance and Mutability
Lists are mutable, meaning you can change their contents without creating a new list.
Lists allow fast appends and efficient iteration, but inserting/removing from the middle can be slower (O(n)).
🪢 Tuples
🔹 What Is a Tuple?
A tuple is like a list, but immutable.
You can’t change its contents once created.
python
Copy
Edit
coordinates = (10.0, 20.5)
Tuple unpacking
x, y = coordinates
🔹 When to Use Tuples
When data shouldn’t change (e.g., dates, positions).
As dictionary keys (since they’re hashable).
🎯 Sets
🔹 What Is a Set?
A set is an unordered collection of unique items.
python
Copy
Edit
colors = {“red”, “blue”, “green”, “blue”} # “blue” is stored only once
🔹 Common Set Operations
python
Copy
Edit
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}
🔹 When to Use Sets
For fast membership testing (x in set is O(1)).
To remove duplicates from a list: set(my_list).
🗂️ Dictionaries
🔹 What Is a Dictionary?
A dictionary stores key-value pairs.
python
Copy
Edit
person = {
“name”: “Alice”,
“age”: 30,
“is_student”: False
}
🔹 Accessing and Modifying
python
Copy
Edit
print(person[“name”]) # “Alice”
print(person.get(“age”)) # 30
person[“age”] = 31 # Update value
person[“email”] = “a@example.com” # Add new key-value
🔹 Common Methods
Method Description
get(key) Safe access (returns None if key not found)
keys() Returns all keys
values() Returns all values
items() Returns key-value pairs
🔹 Iterating Over Dictionaries
python
Copy
Edit
for key, value in person.items():
print(f”{key}: {value}”)
🔹 When to Use Dictionaries
When you want to associate values with labels (e.g., mapping names to phone numbers).
Fast lookups and updates by key.
🧠 Choosing the Right Collection
Task Recommended Collection
Store ordered items with changes list
Store fixed, ordered data tuple
Store unique items, fast membership checks set
Associate values with named keys dict
Real-world analogies:
list: a shopping list (order matters, items can repeat)
tuple: GPS coordinates (fixed data)
set: a collection of tags (unique, unordered)
dict: a contact book (name → phone number)
✅ Summary
Lists are the most versatile collection for ordered, changeable data.
Tuples are like read-only lists, great for fixed data.
Sets ensure uniqueness and offer fast lookups.
Dictionaries allow mapping keys to values for organized data retrieval.
🧪 Practice Time!
Try these small exercises:
Create a list of your five favorite foods. Add two more, then remove one.
Make a dictionary of three friends’ names and their ages. Update one age.
Use a set to find unique letters in the word “mississippi”.
Write a list comprehension to create a list of even numbers from 1 to 20.
Make a tuple to represent a 2D point (x, y) and unpack it into two variables.