Python Data Structures
Python's four core built-in collections — Lists, Tuples, Sets and Dictionaries — how to create, access, modify and choose between them, plus comprehensions.
Until now, each variable has held just one value. But real-world data usually comes in collections — a list of students, a set of unique tags, a dictionary of user profiles. Python gives you four core built-in data structures to handle this: Lists, Tuples, Sets, and Dictionaries.
1. Why Do We Need Data Structures?
What is it?
A data structure is a way of organizing and storing multiple pieces of data together so they can be used efficiently.
Why do we use it?
Imagine tracking marks for 40 students. Creating 40 separate variables (marks1, marks2, ... marks40) would be unmanageable. A single list can hold all 40 values, and you can loop through them, sort them, search them, and modify them easily.
Real-World Example
- A list of products in a shopping cart.
- A set of unique visitor IDs to a website.
- A dictionary mapping usernames to their profile information.
2. Lists
What is it?
A list is an ordered, changeable (mutable) collection that can hold multiple values — even of different types — in a single variable.
Definition: A list is an ordered collection of items that can be changed (added to, removed from, or modified) after creation.
Creation
pythonfruits = ["apple", "banana", "cherry"] mixed = [1, "hello", 3.14, True] empty_list = []
Access (Indexing & Slicing)
Python indexing starts at 0, not 1.
pythonfruits = ["apple", "banana", "cherry", "mango"] print(fruits[0]) # apple (first item) print(fruits[-1]) # mango (last item) print(fruits[1:3]) # ['banana', 'cherry'] (slicing)
Explanation: fruits[-1] uses negative indexing to count from the end. Slicing [1:3] gives items from index 1 up to (but not including) index 3.
Modification
pythonfruits[1] = "blueberry" print(fruits) # ['apple', 'blueberry', 'cherry', 'mango']
Adding Items
pythonfruits.append("orange") # adds to the end fruits.insert(1, "grape") # adds at a specific position fruits.extend(["kiwi", "fig"]) # adds multiple items at once
Deletion
pythonfruits.remove("banana") # removes by value fruits.pop() # removes and returns the last item fruits.pop(0) # removes item at index 0 del fruits[1] # removes item at index 1 fruits.clear() # removes everything
Comparison Table — remove() vs pop()
remove() | pop() | |
|---|---|---|
| Removes by | Value | Index (default: last item) |
| Returns | Nothing | The removed item |
| Error if missing | Yes, if value not found | Yes, if index invalid |
Common List Methods
| Method | Purpose |
|---|---|
append(x) | Add item to the end |
insert(i, x) | Insert item at position i |
remove(x) | Remove first occurrence of value x |
pop(i) | Remove and return item at index i |
sort() | Sort the list in place |
reverse() | Reverse the list in place |
index(x) | Find the position of value x |
count(x) | Count occurrences of x |
copy() | Create a shallow copy of the list |
Iteration
pythonfor fruit in fruits: print(fruit)
List Comprehension
A compact way to build a new list from an existing sequence.
pythonsquares = [x ** 2 for x in range(1, 6)] print(squares) # [1, 4, 9, 16, 25] even_only = [x for x in range(1, 11) if x % 2 == 0] print(even_only) # [2, 4, 6, 8, 10]
Explanation: [expression for item in sequence if condition] — Python builds a new list by evaluating the expression for every item that passes the (optional) condition.
Real-World Example
Storing all product names in a shopping cart, or all marks scored by a student across subjects.
pythoncart = ["Shoes", "T-Shirt", "Watch"] marks = [85, 90, 78, 92] average = sum(marks) / len(marks) print(average)
Common Mistakes
- Forgetting Python indexing starts at
0, not1. - Trying to access an index that doesn't exist →
IndexError. - Confusing
remove()(by value) withpop()(by index). - Modifying a list while looping over it directly, which can cause skipped items.
Important Points
- Lists are mutable — they can change after creation.
- Lists maintain insertion order.
- Lists can hold mixed data types, though it's best practice to keep one type per list when possible.
Practice
- Create a list of 5 numbers and print their sum and average.
- Use list comprehension to create a list of cubes of numbers from 1 to 10.
3. Tuples
What is it?
A tuple is an ordered collection just like a list, but it is immutable — once created, it cannot be changed.
Definition: A tuple is an ordered, unchangeable collection of items.
Creation
pythoncoordinates = (10, 20) single_item_tuple = (5,) # comma is required for a single-item tuple! empty_tuple = ()
Access
Tuples support the same indexing and slicing as lists.
pythonpoint = (10, 20, 30) print(point[0]) # 10 print(point[-1]) # 30 print(point[0:2]) # (10, 20)
Why Can't Tuples Be Modified?
pythonpoint = (10, 20) point[0] = 99 # TypeError: 'tuple' object does not support item assignment
Tuples don't allow reassigning, adding, or removing items after creation — this is the whole point (no pun intended) of using them.
Common Tuple Methods
Since tuples are immutable, they only have two built-in methods:
| Method | Purpose |
|---|---|
count(x) | Count occurrences of x |
index(x) | Find position of x |
Iteration
pythonfor coord in (10, 20, 30): print(coord)
Real-World Example
Tuples are perfect for data that should never change, like geographic coordinates, RGB color values, or a fixed set of days in a week.
pythonred = (255, 0, 0) days = ("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun")
Tuple Unpacking
pythonpoint = (10, 20) x, y = point print(x, y) # 10 20
Common Mistakes
- Forgetting the trailing comma when creating a single-item tuple:
(5)is just the integer5, not a tuple — you need(5,). - Trying to modify a tuple and being confused by the
TypeError.
Important Points
- Tuples are faster than lists for fixed data (slightly less memory overhead).
- Use tuples when the data should never change during the program.
- Tuples can be used as dictionary keys; lists cannot (because lists are mutable).
Practice
- Create a tuple of your favorite three colors and print each one using a loop.
- Try modifying a tuple and observe the error Python gives you.
Comparison Table — List vs Tuple
| List | Tuple | |
|---|---|---|
| Mutability | Mutable (can change) | Immutable (cannot change) |
| Syntax | [1, 2, 3] | (1, 2, 3) |
| Performance | Slightly slower | Slightly faster |
| Use case | Data that changes often | Fixed data that shouldn't change |
| Can be a dictionary key? | No | Yes |
4. Sets
What is it?
A set is an unordered collection of unique items — duplicates are automatically removed.
Definition: A set is a collection of unique, unordered items.
Creation
pythonfruits = {"apple", "banana", "cherry"} numbers_with_duplicates = {1, 2, 2, 3, 3, 3} print(numbers_with_duplicates) # {1, 2, 3} - duplicates removed automatically empty_set = set() # NOTE: {} creates an empty dictionary, not a set!
Access
Sets are unordered, so you cannot access items by index (fruits[0] will cause an error). You can only check membership or iterate.
pythonprint("apple" in fruits) # True
Modification
pythonfruits.add("mango") fruits.update(["kiwi", "fig"])
Deletion
pythonfruits.remove("banana") # error if not found fruits.discard("banana") # no error even if not found fruits.pop() # removes a random item (sets have no order)
Set Operations (Very Useful in Practice)
pythona = {1, 2, 3, 4} b = {3, 4, 5, 6} print(a.union(b)) # {1, 2, 3, 4, 5, 6} - all items from both print(a.intersection(b)) # {3, 4} - common items print(a.difference(b)) # {1, 2} - in a but not in b print(a.symmetric_difference(b)) # {1, 2, 5, 6} - in either, but not both
Iteration
pythonfor fruit in fruits: print(fruit)
Real-World Example
Removing duplicate entries from a list of email addresses, or finding common interests between two users (intersection of their interest sets).
pythonvisitor_ids = [101, 102, 101, 103, 102] unique_visitors = set(visitor_ids) print(len(unique_visitors)) # 3
Common Mistakes
- Using
{}expecting an empty set —{}actually creates an empty dictionary. Useset()for an empty set. - Trying to access set items by index, e.g.
fruits[0]→TypeError. - Assuming sets preserve insertion order — they don't guarantee any particular order.
Important Points
- Sets automatically eliminate duplicate values.
- Sets are unordered — no indexing.
- Extremely useful for membership testing (
in) and removing duplicates quickly.
Practice
- Create two sets of numbers and find their union and intersection.
- Remove duplicates from a list using a set.
5. Dictionaries
What is it?
A dictionary stores data as key-value pairs — instead of accessing items by position (like a list), you access them by a unique key.
Definition: A dictionary is a collection of key-value pairs, where each key maps to a specific value.
Creation
pythonstudent = { "name": "Rohan", "age": 21, "course": "Computer Science" }
Access
pythonprint(student["name"]) # Rohan print(student.get("age")) # 21 print(student.get("grade", "Not Found")) # Not Found (safe access with default)
Explanation: student["name"] raises a KeyError if the key doesn't exist. student.get("key", default) is safer — it returns a default value instead of crashing.
Modification
pythonstudent["age"] = 22 # update existing key student["email"] = "rohan@mail.com" # add a new key
Deletion
pythondel student["email"] student.pop("age") student.clear()
Common Dictionary Methods
| Method | Purpose |
|---|---|
keys() | Returns all keys |
values() | Returns all values |
items() | Returns all key-value pairs |
get(key, default) | Safely access a value |
update({...}) | Add/update multiple keys at once |
pop(key) | Remove a key and return its value |
Iteration
pythonstudent = {"name": "Rohan", "age": 21, "course": "CS"} for key, value in student.items(): print(key, ":", value)
Output:
name : Rohan
age : 21
course : CSDictionary Comprehension
pythonsquares = {x: x ** 2 for x in range(1, 6)} print(squares) # {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
Real-World Example
Dictionaries are perfect for structured data like a user profile, a product catalog entry, or a JSON API response.
pythonuser_profile = { "username": "rohan21", "email": "rohan21@mail.com", "is_active": True }
Common Mistakes
- Accessing a missing key with
[]instead of.get(), causing aKeyError. - Assuming dictionaries are indexed by number — they're indexed by key, not position.
- Using a mutable type (like a list) as a dictionary key — only immutable types (strings, numbers, tuples) can be keys.
Important Points
- Dictionary keys must be unique and immutable (strings, numbers, or tuples).
- Since Python 3.7, dictionaries maintain insertion order.
.get()is the safe way to access a key that might not exist.
Practice
- Create a dictionary storing a product's name, price, and quantity, then print each using
.items(). - Use dictionary comprehension to create a dictionary mapping numbers 1–5 to their cubes.
Comparison Table — Set vs Dictionary
| Set | Dictionary | |
|---|---|---|
| Stores | Unique values only | Key-value pairs |
| Syntax | {1, 2, 3} | {"key": "value"} |
| Access | Membership check (in) | By key |
| Order | Unordered | Insertion order preserved (3.7+) |
Overall Comparison Table — Choosing the Right Structure
| Structure | Ordered? | Mutable? | Duplicates Allowed? | Access By | Best For |
|---|---|---|---|---|---|
| List | Yes | Yes | Yes | Index | General-purpose ordered collection |
| Tuple | Yes | No | Yes | Index | Fixed data that shouldn't change |
| Set | No | Yes | No | Membership (in) | Removing duplicates, set operations |
| Dictionary | Yes (3.7+) | Yes | Keys must be unique | Key | Structured, labeled data |
Common Beginner Mistakes — Summary
- Confusing list indexing (starts at 0) and slicing rules.
- Trying to modify a tuple.
- Using
{}when you meant an empty set (set()). - Accessing a dictionary key that doesn't exist without using
.get(). - Forgetting sets have no guaranteed order and cannot be indexed.
Cheat Sheet — Data Structures
python# List lst = [1, 2, 3] lst.append(4); lst.remove(1); lst[0] = 99 # Tuple tup = (1, 2, 3) x, y, z = tup # Set s = {1, 2, 3} s.add(4); s.union({5, 6}); s.intersection({2, 3}) # Dictionary d = {"key": "value"} d["key"]; d.get("key", "default"); d.items()
Mini Project: Student Marks Manager
Objective
Build a program to store, update, and analyze marks for multiple students using a dictionary of lists.
Requirements
- Store each student's name and their list of subject marks.
- Calculate each student's total and average marks.
- Find the topper (student with the highest average).
Concepts Used
Dictionaries, lists, loops, functions (basic use), comparison operators.
Complete Code
pythonstudents = { "Aditi": [85, 90, 78], "Rohan": [70, 88, 92], "Zara": [95, 91, 89] } topper_name = None topper_average = 0 for name, marks in students.items(): total = sum(marks) average = total / len(marks) print(f"{name}: Total = {total}, Average = {average:.2f}") if average > topper_average: topper_average = average topper_name = name print(f"\nTopper: {topper_name} with an average of {topper_average:.2f}")
Code Explanation
studentsis a dictionary where each key (student name) maps to a list of marks.students.items()lets us loop through both the name and the marks list together.- We track the highest average seen so far to determine the topper, updating
topper_namewhenever we find a higher average.
Sample Output
Aditi: Total = 253, Average = 84.33
Rohan: Total = 250, Average = 83.33
Zara: Total = 275, Average = 91.67
Topper: Zara with an average of 91.67Possible Improvements
- Allow adding new students and marks interactively via
input(). - Add grade calculation (A/B/C/Fail) for each student based on average.
- Sort and display all students from highest to lowest average.
Challenge Task
Extend the program to also find the topper per subject (assuming subject names are tracked alongside marks).
Interview Questions
Q1. What is the difference between a list and a tuple? Answer: A list is mutable (can be changed after creation), while a tuple is immutable. Lists use [], tuples use ().
Q2. Why would you use a set instead of a list? Answer: When you need to store unique values only and don't care about order, or when you need fast membership testing and set operations like union/intersection.
Q3. How do you safely access a dictionary key that might not exist? Answer: Use .get(key, default_value) instead of dictionary[key], which avoids a KeyError if the key is missing.
Q4. Can a list be used as a dictionary key? Why or why not? Answer: No — dictionary keys must be immutable (hashable), and lists are mutable, so they cannot be used as keys. Tuples can be used instead.
Q5. What's the difference between `remove()` and `discard()` in a set? Answer: remove() raises an error if the value isn't found; discard() does not raise an error in that case.
Q6. Does a dictionary maintain order? Answer: Yes, since Python 3.7, dictionaries maintain the order in which keys were inserted.
Practice Questions
Beginner
- Create a list of 5 fruits and print the second and last item.
- Create a tuple of 3 numbers and print their sum.
- Create a set from a list with duplicate values and print the unique result.
- Create a dictionary with 3 key-value pairs and print all keys.
- Use a list comprehension to generate a list of squares from 1 to 10.
Intermediate
- Write a program that removes duplicate values from a list using a set, while preserving the original order.
- Create a dictionary of 5 products with their prices, then print the most expensive product.
- Write a program to merge two dictionaries into one.
- Given a list of numbers, use list comprehension to create a new list containing only the even numbers, squared.
- Write a program that counts how many times each word appears in a sentence, using a dictionary.
Challenge
- Given two sets of students enrolled in two different courses, find students enrolled in both, and students enrolled in only one.
- Write a program that takes a list of student dictionaries (each with
nameandmarks) and prints them sorted by marks, highest first. - Build a simple contact book using a dictionary where each key is a name and each value is another dictionary containing phone number and email.