Part 2
Data Structures & Functions
Lists, Tuples, Dicts, Sets & Functions
1. Lists
Lists are ordered, mutable collections that can hold mixed data types.
fruits = ["apple", "banana", "cherry"]
[Link]("mango")
[Link]("banana")
print(fruits[0]) # apple
print(fruits[-1]) # mango
print(fruits[1:3]) # slicing
print(len(fruits)) # 3
2. Tuples
Tuples are like lists but immutable — once created, they cannot be changed.
point = (10, 20)
x, y = point # unpacking
print(x, y) # 10 20
3. Dictionaries
Dictionaries store key-value pairs and provide fast lookups.
student = {"name": "Rafi", "age": 21, "dept": "CSE"}
print(student["name"]) # Rafi
student["age"] = 22
for key, value in [Link]():
print(key, "->", value)
4. Sets
Sets store unique, unordered elements — useful for removing duplicates and 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}
5. Functions
Functions group reusable logic. They can take parameters and return values.
def greet(name, greeting="Hello"):
return f"{greeting}, {name}!"
print(greet("Alice"))
print(greet("Bob", "Hi"))
def total(*nums):
return sum(nums)
print(total(1, 2, 3, 4)) # 10
6. List Comprehensions
A concise way to build lists from existing iterables.
squares = [x**2 for x in range(6)]
evens = [x for x in range(20) if x % 2 == 0]
print(squares)
print(evens)
Practice Exercises
• Given a list of numbers, return only the even ones using a list comprehension.
• Write a function that counts word frequency in a sentence using a dictionary.
• Merge two lists into one without duplicate values.