Zero to Python Hero – Part 5/10: Essential Data Structures in Python: Lists, Tuples, Sets & Dictionaries
Rajesh- 0
The fundamental way of storing, accessing and manipulating of data in python is data structures. Python provides an convenient and adaptable collection of objects to store and data and sort it in different ways, be it a list, a tuple, a dictionary or a set.

In the current article, we will go through the most critical data structures in Python: Lists, Tuples, Sets, and Dictionaries. We will also investigate practical built-in methods that are used on these data structures, investigate mutability and performance behavior of the data structure and lastly, provide a few exercises to practice by hand.
Lists
A Python list is a mutable collection of elements that is ordered. You can place anything in a list even another list!
my_list = [1, 2, 3, 4, 5]
Key Operations
- append() – Add an element to the end.
- insert() – Add at a specific index.
- pop() – Remove and return an item.
- remove() – Delete by value.
- sort() – Sort the list in-place.
- reverse() – Reverse the list in-place.
- Slicing – Extract subsets: my_list[1:3]
Real-World Example
Imagine storing a student’s marks in different subjects:
marks = [89, 76, 91, 85]
average = sum(marks) / len(marks)
print("Average Marks:", average)
Common Pitfall
Modifying a list while iterating over it can lead to unexpected behavior.
Tuple
A tuple is analogous to a list but it is immutable. As soon as it has been defined, there is nothing you can do to alter its material.
my_tuple = (10, 20, 30) You can also define single-element tuples like this: single_element = (5,) # Note the comma!
Key Operations
- Access using index: my_tuple[0]
- Count occurrences: my_tuple.count(20)
- Find index: my_tuple.index(30)
Real-World Example
Useful for storing constant data like coordinates:
location = (17.385, 78.4867)
print(f"Latitude: {location[0]}, Longitude: {location[1]}")
Common Pitfall
Trying to modify a tuple will raise a TypeError.
Sets
The set is also an ordered collection of unique things. They can be very useful in testing of membership and removal of duplicates.
my_set = {1, 2, 3, 4, 4, 2}
print(my_set) # Output: {1, 2, 3, 4}
Key Operations
- add() – Add an element.
- remove() – Remove an item (throws error if not found).
- discard() – Safe remove.
- union(), intersection(), difference() – Set operations.
- in – Membership test.
Real-World Example
Removing duplicates from a list:
students = ["Alice", "Bob", "Alice", "David"] unique_students = set(students) print(unique_students)
Dictionaries
A dictionary stores data as key-value pairs. It’s an unordered and mutable data structure, and keys must be unique.
person = {
"name": "Raj",
"age": 30,
"city": "Hyderabad"
}
Key Operations
- get() – Safe retrieval.
- keys() / values() / items() – Access different parts.
- update() – Merge dictionaries.
- pop() – Remove a key.
Real-World Example
Storing user profiles:
user = {"username": "coder123", "followers": 540}
print(f"{user['username']} has {user['followers']} followers.")
Common Pitfall
Accessing a key that doesn’t exist without get() can raise a KeyError.
Built-in Functions
Python includes several built-in functions that make working with these data structures easier.
List of Useful Functions
| Function | Purpose |
| len() | Returns number of items |
| sorted() | Returns a new sorted list |
| sum() | Returns the sum (works with numeric data) |
| min() / max() | Find smallest/largest value |
| zip() | Combine multiple iterables |
| enumerate() | Return index and item |
| type() | Identify data type |
Examples
names = ['Alice', 'Bob', 'Charlie']
scores = [85, 90, 95]
for name, score in zip(names, scores):
print(f"{name} scored {score}")
Mutability & Performance Comparison
Understanding mutability and performance helps in choosing the right data structure.
Mutability Overview
| Structure | Mutable? | Ordered? | Allows Duplicates? |
| List | ✅ Yes | ✅ Yes | ✅ Yes |
| Tuple | ❌ No | ✅ Yes | ✅ Yes |
| Set | ✅ Yes | ❌ No | ❌ No |
| Dictionary | ✅ Yes | ❌ No | ❌ No (for keys) |
Performance Considerations
| Operation | List | Tuple | Set | Dictionary |
| Indexing | O(1) | O(1) | ❌ | O(1) |
| Membership Test | O(n) | O(n) | O(1) | O(1) |
| Insertion/Deletion | O(n) worst | ❌ | O(1) avg | O(1) avg |
- Use lists when order and mutability matter.
- Use tuples for fixed collections (e.g., function arguments).
- Use sets for uniqueness and fast lookups.
- Use dictionaries for mappings and quick key access.
Exercises
Try solving these problems to reinforce your understanding:
1. Average Calculator
Write a program to accept marks of 5 students and print the average using a list.
marks = [87, 91, 78, 85, 89]
print("Average:", sum(marks)/len(marks))
2. Find Unique Words
Take a sentence from a user and print all unique words.
sentence = "Python is simple and Python is powerful"
words = set(sentence.split())
print("Unique words:", words)
3. Student Info Dictionary
Create a dictionary to store a student’s name, age, and grades. Print the keys and values.
student = {"name": "Kiran", "age": 16, "grades": [85, 90, 92]}
for key, value in student.items():
print(f"{key}: {value}")
4. List Filtering with Comprehension
Generate a list of even numbers from 1 to 50 using list comprehension.
evens = [x for x in range(1, 51) if x % 2 == 0] print(evens)
5. Immutable Coordinates
Store three coordinate points in a tuple and print them.
points = ((2, 3), (4, 5), (6, 7))
for x, y in points:
print(f"x: {x}, y: {y}")
6. Top Scorer from Dictionary
Given a dictionary of students and scores, find the topper.
scores = {"Aman": 75, "Bhavya": 88, "Ravi": 92}
topper = max(scores, key=scores.get)
print("Topper:", topper)
7. Set Operations
Write a program to find common elements in two sets.
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
print("Intersection:", a & b)
Conclusion
The effective core data structures of Python, namely lists, tuples, sets, and dictionaries, make the coding efficient and expressive. Knowing when and why to apply this or that structure will assist you to write cleaner, faster and easier maintainable programs.
When you are constructing a student grading system, scraping web data, or just managing files on your system, the ability to control the data at hand with ease and adaptability is available through the mastery of these structures.
Keep practicing. Get into more about each structure. And bear in mind: it is all due to the appropriate data structure.
- Zero to Python Hero – Part 6/10: Functions and Modules in Python
- Zero to Python Hero – Part 5/10: Essential Data Structures in Python: Lists, Tuples, Sets & Dictionaries
- Top 5 Skills Every Engineer Should Learn in 2026
- Zero to Python Hero - Part 4/10 : Control Flow: If, Loops & More (with code examples)
- Zero to Python Hero - Part 3/10 : Understanding Type Casting, Operators, User Input and String formatting (with Code Examples)
Author
-
Rajesh Yerremshetty is an IIT Roorkee MBA graduate with 10 years of experience in Data Analytics and AI. He has worked with leading organizations, including CarDekho.com, Vansun Media Tech Pvt. Ltd., and STRIKIN.com, driving innovative solutions and business growth through data-driven insights.
View all posts
