Python β€’ Data Structures

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)

list_creation.py
# 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

list_methods.py
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)

comprehensions.py
# 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

πŸ“Œ Slicing syntax: 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

tuple_details.py
# 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

set_basics.py
# 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.)

set_ops.py
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

FeatureListTupleSetFrozenset
Orderedβœ“βœ“βœ—βœ—
Mutableβœ“βœ—βœ“βœ—
Allows duplicatesβœ“βœ“βœ—βœ—
Indexed / Slicableβœ“βœ“βœ—βœ—
Membership (in) speedO(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.py
"""
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()
πŸ’‘ Project Highlights:
- 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())
Write your code here – solution not shown.
2. Reverse a List Without Using reverse() or slicing
Write your code here – solution not shown.
3. Check if a Tuple is Empty
Write your code here – solution not shown.

⚑ Intermediate Level

4. Flatten a Nested List
Write your code here – solution not shown.
5. Symmetric Difference of Two Sets (without ^ operator)
Write your code here – solution not shown.
6. Sort a List of Tuples by Second Element
Write your code here – solution not shown.

πŸ”₯ Advanced Level (Company Interview)

1. Longest Increasing Subsequence (LIS)
Write your code here – solution not shown.

Test Cases: [10,9,2,5,3,7,101,18] β†’ 4

2. Merge Overlapping Intervals
Write your code here – solution not shown.
3. Group Anagrams from a List of Strings
Write your code here – solution not shown.
4. Rotate a List In‑Place (O(1) extra space)
Write your code here – solution not shown.
5. Find the k‑th Largest Element (without full sort)
Write your code here – solution not shown.