Day 5 – Python Data Structures: Lists,
Tuples, Sets, and Dictionaries
1. Introduction to Data Structures in Python
Data structures allow you to store, organize, and manipulate data efficiently. Python provides
several built-in data structures, and the most fundamental ones are:
● list
● tuple
● set
● dict (dictionary)
Each serves a different purpose and has specific use cases, advantages, and behaviors.
2. Lists
Definition:
A list is an ordered, mutable (changeable), indexable collection of items.
Syntax:
python
CopyEdit
my_list = [1, 2, 3, "hello", True]
Key Features:
● Allows duplicate values
● Elements can be of mixed types
● Supports indexing and slicing
Creating Lists
python
CopyEdit
empty_list = []
numbers = [1, 2, 3, 4, 5]
mixed = ["apple", 10, 3.14, False]
Indexing and Slicing
python
CopyEdit
my_list = [10, 20, 30, 40, 50]
print(my_list[0]) # 10 (first element)
print(my_list[-1]) # 50 (last element)
print(my_list[1:4]) # [20, 30, 40]
Modifying Lists
python
CopyEdit
my_list[2] = 99
print(my_list) # [10, 20, 99, 40, 50]
List Methods
Method Description
append() Add element to the end
insert(i, Insert x at position i
x)
pop() Remove and return last item
remove(x) Remove first occurrence of x
sort() Sort list in ascending order
reverse() Reverse the list
extend() Add all elements from another list
Example:
python
CopyEdit
fruits = ["apple", "banana"]
[Link]("cherry")
[Link](1, "orange")
[Link]("banana")
print(fruits) # ['apple', 'orange', 'cherry']
Looping Through a List
python
CopyEdit
for item in fruits:
print(item)
Nested Lists
python
CopyEdit
matrix = [[1, 2], [3, 4], [5, 6]]
print(matrix[1][0]) # 3
3. Tuples
Definition:
A tuple is an ordered, immutable collection.
Syntax:
python
CopyEdit
my_tuple = (1, 2, 3, "hello", True)
Key Features:
● Immutable (cannot be changed after creation)
● More memory-efficient than lists
● Useful for fixed collections
Creating Tuples
python
CopyEdit
empty_tuple = ()
single_item = (5,) # Note the comma!
values = (1, 2, 3, 4)
Accessing Elements
python
CopyEdit
print(values[0]) # 1
print(values[-1]) # 4
Tuple Unpacking
python
CopyEdit
a, b, c = (10, 20, 30)
print(a) # 10
When to Use Tuples:
● To store constant data
● As keys in dictionaries (if elements are immutable)
● For function return values
4. Sets
Definition:
A set is an unordered, unindexed, mutable, and unique collection of elements.
Syntax:
python
CopyEdit
my_set = {1, 2, 3}
Key Features:
● No duplicate elements
● Unordered (no indexing/slicing)
● Useful for membership testing and set operations
Creating Sets
python
CopyEdit
empty_set = set()
unique_items = {1, 2, 2, 3, 4}
print(unique_items) # {1, 2, 3, 4}
Set Methods
Method Description
add(x) Add element x to the set
remove(x) Remove x (raises error if not found)
discard(x) Remove x (does nothing if not found)
pop() Remove and return arbitrary element
clear() Remove all elements
update() Add multiple elements
Set Operations
Operation Symbol / Method
Union `set1
Intersection set1 & set2 or
[Link](set2)
Difference set1 - set2
Symmetric Difference set1 ^ set2
Example:
python
CopyEdit
a = {1, 2, 3}
b = {3, 4, 5}
print(a | b) # {1, 2, 3, 4, 5}
print(a & b) # {3}
print(a - b) # {1, 2}
5. Dictionaries
Definition:
A dict is a collection of key-value pairs. It is unordered (as of Python <3.7), mutable, and
allows fast lookups.
Syntax:
python
CopyEdit
student = {"name": "Alice", "age": 22, "grade": "A"}
Key Features:
● Keys must be unique and immutable (strings, numbers, tuples)
● Values can be of any type
● Supports nesting (dict inside dict)
Accessing Elements
python
CopyEdit
print(student["name"]) # Alice
print([Link]("grade")) # A
Adding / Updating Elements
python
CopyEdit
student["age"] = 23
student["city"] = "New York"
Removing Elements
python
CopyEdit
[Link]("grade")
del student["city"]
[Link]() # Empties the dictionary
Useful Dictionary Methods
Method Description
get(key) Get value for key or return
None
keys() Returns all keys
values() Returns all values
items() Returns all key-value pairs
update(dic Merges another dictionary
t2)
Looping Through Dictionary
python
CopyEdit
for key, value in [Link]():
print(f"{key}: {value}")
Nested Dictionaries
python
CopyEdit
users = {
"user1": {"name": "Alice", "age": 30},
"user2": {"name": "Bob", "age": 25}
}
print(users["user1"]["name"]) # Alice
6. Summary Table
Data Ordere Mutabl Duplicate Indexe Use Case
Structure d e s d
List Yes Yes Yes Yes General-purpose ordered
collection
Tuple Yes No Yes Yes Fixed-size ordered data
Set No Yes No No Unique items, set operations
Dict No Yes Keys: No No Key-value mapping
7. Exercises
1. List Practice:
○ Create a list of five fruits and:
■ Add a fruit
■ Remove the second fruit
■ Print all fruits using a loop
2. Tuple Practice:
○ Create a tuple of coordinates (x, y) and unpack it.
3. Set Practice:
○ Create two sets: {1,2,3,4} and {3,4,5,6}
○ Perform union, intersection, and difference
4. Dictionary Practice:
○ Create a dictionary for a book with keys: "title", "author", and "year"
○ Add a key "price" and update "year"
○ Print all key-value pairs