Lists, Tuples & Sets Deep Dive
Master every method, slicing trick, comprehension, and performance nuance. Then build a realβworld student grade manager that ties everything together with variables, loops, conditionals, and type casting.
List
Mutable, ordered, duplicates allowed
Tuple
Immutable, ordered, duplicates allowed
Set
Mutable, unordered, no duplicates
Frozenset
Immutable version of set
Lists β The Workhorse of Python
A list is a dynamic array that can hold any mix of data types. You can modify it after creation β add, remove, sort, and slice.
Creating & Accessing (Deep Dive)
# Different ways to create lists
empty = [] # empty list
numbers = [1, 2, 3] # literal
mixed = [42, "hello", 3.14, True] # mixed types
nested = [[1,2], [3,4]] # list of lists
from_range = list(range(5)) # [0,1,2,3,4]
from_string = list("Python") # ['P','y','t','h','o','n']
# Accessing elements
print(numbers[0]) # 1
print(numbers[-1]) # 3 (last)
print(numbers[1:3]) # [2,3] (slice)
print(numbers[::-1]) # [3,2,1] (reverse slice)
All Important List Methods
lst = [3, 1, 4, 1, 5, 9]
# Adding elements
lst.append(2) # [3,1,4,1,5,9,2] β add to end
lst.insert(2, 99) # [3,1,99,4,1,5,9,2] β insert at index
lst.extend([6,7]) # [3,1,99,4,1,5,9,2,6,7] β add iterable
# Removing elements
lst.remove(1) # removes first occurrence of 1
popped = lst.pop() # removes and returns last (7)
popped_index = lst.pop(3) # removes index 3 (4)
# Searching & counting
idx = lst.index(5) # index of first 5
cnt = lst.count(1) # how many 1's
# Sorting & reversing
lst.sort() # ascending inβplace
lst.sort(reverse=True)# descending
lst.reverse() # reverse order
# Copying (shallow vs deep)
copy1 = lst.copy() # shallow copy (list of same objects)
copy2 = lst[:] # also a shallow copy
# Clearing
lst.clear() # empty list
print("Original after ops:", lst)
List Comprehensions (Powerful OneβLiners)
# Basic: [expression for item in iterable]
squares = [x**2 for x in range(1,6)] # [1,4,9,16,25]
# With condition
evens = [x for x in range(10) if x % 2 == 0] # [0,2,4,6,8]
# Nested loops
pairs = [(x,y) for x in range(3) for y in range(2)] # [(0,0),(0,1),(1,0)...]
# Matrix flattening
matrix = [[1,2,3],[4,5,6]]
flat = [num for row in matrix for num in row] # [1,2,3,4,5,6]
# With ifβelse (ternary)
labels = ["even" if x%2==0 else "odd" for x in range(5)]
Slicing & Performance Tips
list[start:stop:step] β all optional.β‘ Performance:
append() is O(1) amortized; insert() and pop() from middle are O(n). Use collections.deque for fast left pops.
Tuples β Immutable Sequences
Tuples are immutable (cannot be changed after creation). Use them for fixed data, dictionary keys, and when you want to guarantee data integrity.
Creating & Packing/Unpacking
# Creation
t1 = (1,2,3) # literal
t2 = 4,5,6 # packing (parentheses optional)
t3 = tuple([7,8,9]) # from iterable
single = (42,) # comma needed for singleβelement tuple
# Unpacking
a, b, c = t1 # a=1, b=2, c=3
*rest, last = t2 # rest=[4,5], last=6 (extended unpacking)
# Immutability β can't modify, but can reassign variable
# t1[0] = 100 β TypeError
# Methods
print(t1.count(2)) # 1
print(t1.index(3)) # 2
# Tuple as dictionary key (lists cannot)
coordinates = {(40.7128, -74.0060): "New York"}
When to Use Tuple vs List
- Tuple: Fixed data (days of week, RGB values, coordinates), dictionary keys, returning multiple values from functions.
- List: Dynamic collections that need modification (user inputs, growing datasets, sorting).
Sets β Unordered, Unique, Fast
Sets are mutable but contain only unique elements. They use hash tables, giving O(1) average membership tests. Great for deduplication and mathematical operations.
Creating & Basic Ops
# Creation
s1 = {1,2,3,3,4} # {1,2,3,4} β duplicates removed
s2 = set([1,2,3]) # from list
empty_set = set() # {} is dict, not empty set!
# Add / Remove
s1.add(5) # {1,2,3,4,5}
s1.remove(2) # error if missing
s1.discard(10) # no error if missing
element = s1.pop() # removes arbitrary element
# Membership (fast)
if 3 in s1: print("Found")
Set Algebra (Union, Intersection, etc.)
A = {1,2,3,4}
B = {3,4,5,6}
print(A | B) # union β {1,2,3,4,5,6}
print(A & B) # intersection β {3,4}
print(A - B) # difference β {1,2}
print(B - A) # {5,6}
print(A ^ B) # symmetric difference β {1,2,5,6}
# Methods (same as operators)
print(A.union(B))
print(A.intersection(B))
print(A.difference(B))
print(A.symmetric_difference(B))
# Subset / Superset
print({1,2}.issubset(A)) # True
print(A.issuperset({1,2})) # True
Frozenset β Immutable Set
fs = frozenset([1,2,3]) # immutable
# fs.add(4) β AttributeError
Comparison Table
| Feature | List | Tuple | Set | Frozenset |
|---|---|---|---|---|
| Ordered | β | β | β | β |
| Mutable | β | β | β | β |
| Allows duplicates | β | β | β | β |
| Indexed / Slicable | β | β | β | β |
| Membership (in) speed | O(n) | O(n) | O(1) | O(1) |
| Hashable (can be dict key) | β | β | β | β |
π― Mini Project: Student Grade Manager
This project uses everything you've learned so far: variables, data types, input/output, type casting, loops, conditionals, and collections (lists, tuples, sets). You'll build a program to manage student grades, compute averages, find top performers, and detect duplicates.
"""
Student Grade Manager β A complete mini project
Features:
- Store student records (name, grade, marks list)
- Calculate average, highest, lowest marks per student
- List all students, find toppers
- Detect duplicate student names using a set
- Use loops, conditionals, type casting, lists, tuples, sets
"""
def main():
students = [] # list of tuples: (name, [marks])
all_names = set() # set for duplicate detection
while True:
print("\nπ STUDENT GRADE MANAGER π")
print("1. Add new student")
print("2. View all students & averages")
print("3. Find class topper")
print("4. Check duplicate names")
print("5. Exit")
choice = input("Choose option (1-5): ").strip()
if choice == "1":
# Input with validation
name = input("Enter student name: ").strip()
if name in all_names:
print("β οΈ Name already exists! Duplicate not allowed (using set check).")
continue
# Grade (int)
try:
grade = int(input("Enter grade (1-12): "))
if grade < 1 or grade > 12:
print("Invalid grade. Must be 1-12.")
continue
except ValueError:
print("Invalid input. Grade must be an integer.")
continue
# Marks for 3 subjects (using list)
marks = []
subjects = ["Math", "Science", "English"]
for sub in subjects:
while True:
try:
mark = float(input(f"Enter marks for {sub} (0-100): "))
if 0 <= mark <= 100:
marks.append(mark)
break
else:
print("Marks must be between 0 and 100.")
except ValueError:
print("Please enter a valid number.")
# Store as tuple (name, grade, marks)
students.append((name, grade, marks))
all_names.add(name)
print(f"β
Student {name} added successfully!")
elif choice == "2":
if not students:
print("No students yet.")
continue
# Display all students with average marks
print("\nπ ALL STUDENTS REPORT π")
print(f"{'Name':<15} {'Grade':<6} {'Marks':<20} {'Average':<8}")
print("-" * 55)
for name, grade, marks in students:
avg = sum(marks) / len(marks)
marks_str = ", ".join(str(m) for m in marks)
print(f"{name:<15} {grade:<6} {marks_str:<20} {avg:<8.2f}")
elif choice == "3":
if not students:
print("No students yet.")
continue
# Find student with highest average using loops and conditionals
topper = None
highest_avg = -1
for name, grade, marks in students:
avg = sum(marks) / len(marks)
if avg > highest_avg:
highest_avg = avg
topper = (name, grade, avg)
print(f"π Topper: {topper[0]} (Grade {topper[1]}) with average {topper[2]:.2f}")
elif choice == "4":
# Check duplicate names (already prevented in add, but show set usage)
print(f"Total unique student names: {len(all_names)}")
print(f"List of unique names: {sorted(all_names)}")
# Show if any duplicates were prevented
print("(Duplicates are rejected during addition β set ensures uniqueness)")
elif choice == "5":
print("Goodbye! Keep coding π")
break
else:
print("Invalid option. Please try again.")
if __name__ == "__main__":
main()
- Lists store marks and the list of students
- Tuples hold each student record (immutable after creation)
- Sets ensure unique student names
- Loops iterate over subjects and students
- Conditionals validate input and find topper
- Type casting converts input strings to int/float
- fβstrings format output
- Functions (main) structure the code
Extend it by adding file saving/loading, sorting by grade, or computing subjectβwise toppers.
Practice Problems (Solved)
Strengthen your skills with these detailed solutions.
π° Beginner Level
1. Find the Maximum Element in a List (Without max())
nums = [4, 12, 7, 19, 3, 5]
max_val = nums[0]
for n in nums:
if n > max_val:
max_val = n
print("Maximum:", max_val)2. Remove Duplicates from a List (Preserve Order)
items = [1,2,3,2,4,5,1]
seen = []
for x in items:
if x not in seen:
seen.append(x)
print(seen)3. Count Specific Element in a Tuple (Without .count())
data = (5,3,8,5,9,5,2)
target = 5
count = 0
for x in data:
if x == target:
count += 1
print(f"{target} appears {count} times")β‘ Intermediate Level
4. Merge Two Sorted Lists into One Sorted List (No sort())
a = [1,4,6]; b = [2,3,5]
merged = []; i=j=0
while i < len(a) and j < len(b):
if a[i] < b[j]:
merged.append(a[i]); i+=1
else:
merged.append(b[j]); j+=1
merged.extend(a[i:]); merged.extend(b[j:])
print(merged)5. Find Common Elements in Two Sets (Intersection)
set1 = {"apple", "banana", "cherry"}
set2 = {"banana", "date", "cherry"}
common = set1.intersection(set2)
print("Common:", common)6. Convert List of Tuples to Dictionary
pairs = [("name","Aarav"), ("grade",8), ("marks",84.5)]
student = dict(pairs)
print(student["name"])Unsolved Exercises
Challenge yourself β no solutions here, but you can use the solved examples and the mini project as inspiration.
π° Beginner Level
1. Sum of All Numbers in a List (without sum())
2. Reverse a List Without Using reverse() or slicing
3. Check if a Tuple is Empty
β‘ Intermediate Level
4. Flatten a Nested List
5. Symmetric Difference of Two Sets (without ^ operator)
6. Sort a List of Tuples by Second Element
π₯ Advanced Level (Company Interview)
1. Longest Increasing Subsequence (LIS)
Test Cases: [10,9,2,5,3,7,101,18] β 4