Python Lists: Complete 50-Part Roadmap Notes
Master Python Lists from zero to advanced concepts with dual-language explanations, feature breakdowns, code syntax, memory concepts, errors, practice questions, and a real-world shopping cart project.
Parts 1 - 5: List Introduction, 14 Features & Indexing
English Definition & Interview Answer
A List is an ordered, mutable collection in Python enclosed in square brackets [] that allows duplicate values and can store elements of different data types (heterogeneous).
Hinglish Explanation
List Python mein ek ordered aur mutable collection hoti hai jise square brackets [] ke andar banaya jata hai. Isme hum different data types ki duplicate values ko bhi store kar sakte hain.
14 Important Features of Python Lists
- 1Ordered: Maintains the exact insertion order of items.
- 2Mutable: Items can be modified, added, or removed after creation.
- 3Allows Duplicates: Can store identical elements multiple times.
- 4Heterogeneous Data: Can mix integers, floats, strings, booleans, and objects.
- 5Positive Indexing: Access items starting from index 0 from left to right.
- 6Negative Indexing: Access items starting from index -1 from right to left.
- 7Slicing Support: Extract portions using
[start:stop:step]. - 8Dynamic Size: Automatically grows or shrinks at runtime.
- 9Can Store Lists: Supports nested lists inside lists.
- 10Can Store Objects: Class instances can be stored as elements.
- 11Zero-Based Indexing: First element is strictly at index 0.
- 12Iterable: Can loop over elements using
fororwhileloops. - 13Multi-Level Nesting: Allows lists inside lists to arbitrary depths.
- 14Rich Built-in Methods: Provides
append(),pop(),sort(), etc.
empty_list = []
numbers = [10, 20, 30, 40]
mixed = [10, "Gagan", 5.9, True]
print("First element (index 0):", mixed[0])
print("Second element (index 1):", mixed[1])
print("Last element (index -1):", mixed[-1])
print("Second last (index -2):", mixed[-2])
Second element (index 1): Gagan
Last element (index -1): True
Second last (index -2): 5.9
Parts 6 - 9: Changing & Adding Items (append, insert, extend)
Because lists are mutable, we can update item values or insert new items using three main methods:
| Method | Syntax | Behavior | Example Result |
|---|---|---|---|
| Index Update | list[idx] = val |
Replaces item at index idx |
[10, 20] → [100, 20] |
| append() | list.append(val) |
Adds single item to the end | [1, 2].append(3) → [1, 2, 3] |
| insert() | list.insert(idx, val) |
Inserts item at specified index | [10, 30].insert(1, 20) → [10, 20, 30] |
| extend() | list.extend(iterable) |
Appends individual elements from iterable | [1, 2].extend([3, 4]) → [1, 2, 3, 4] |
append() vs extend() Comparison
append([4, 5]) adds the list as a single nested element [1, 2, 3, [4, 5]].
extend([4, 5]) unpacks and adds individual numbers [1, 2, 3, 4, 5].
Hinglish Comparison
append() poori list ko ek single element banakar add karta hai.
extend() iterable ke saare elements ko alag-alag nikal kar add karta hai.
names = ["Gagan", "Lokesh"]
names[1] = "Aman"
names.append("Rajat")
names.insert(1, "Rahul")
nums = [1, 2]
nums.extend([3, 4])
print("Names List:", names)
print("Extended Nums:", nums)
Extended Nums: [1, 2, 3, 4]
Parts 10 - 13: Removing Items (remove, pop, del, clear)
4 Ways to Remove Elements
- remove(val): Removes first occurrence of specified value.
- pop(idx): Removes & returns item at index (default: last item).
- del list[idx]: Deletes element(s) or entire variable.
- clear(): Removes all elements, leaving an empty list
[].
clear() vs del Difference
clear() list ke saare elements ko remove karta hai lekin list object memory mein rehta hai (empty list []).
del list_name poore variable reference ko delete kar deta hai.
items = [10, 20, 30, 40, 50, 20]
items.remove(20)
removed_val = items.pop(2)
del items[0]
print("Remaining items:", items)
print("Popped value:", removed_val)
items.clear()
print("After clear():", items)
Popped value: 40
After clear(): []
Parts 14 - 16: List Length, Membership & Advanced Slicing
List Length & Membership Operators
len(list) returns total number of elements.
in / not in checks if value exists, returning True or False.
Slicing Syntax: [start : stop : step]
start: Included index (default 0).
stop: Excluded index.
step: Jump rate (negative step reverses list).
numbers = [10, 20, 30, 40, 50, 60]
print("Total elements:", len(numbers))
print("Is 30 in list?", 30 in numbers)
print("Is 100 not in list?", 100 not in numbers)
print("Slice [1:4]:", numbers[1:4])
print("Slice [:3]:", numbers[:3])
print("Slice [2:]:", numbers[2:])
print("Step 2 [::2]:", numbers[::2])
print("Reversed [::-1]:", numbers[::-1])
Is 30 in list? True
Is 100 not in list? True
Slice [1:4]: [20, 30, 40]
Slice [:3]: [10, 20, 30]
Slice [2:]: [30, 40, 50, 60]
Step 2 [::2]: [10, 30, 50]
Reversed [::-1]: [60, 50, 40, 30, 20, 10]
Parts 17 - 23: Concatenation, Repetition, Looping, Sorting & Reversing
| Operation / Method | Syntax | Description |
|---|---|---|
| Concatenation | list1 + list2 |
Combines two lists into a new list |
| Repetition | list * n |
Repeats list items n times |
| Looping | for item in list: |
Iterates through items one by one |
| index() | list.index(val) |
Returns index of first matching value |
| count() | list.count(val) |
Returns total occurrences of value |
| sort() | list.sort(reverse=True) |
Modifies original list in-place |
| sorted() | new_l = sorted(list) |
Returns new sorted list (original unchanged) |
| reverse() | list.reverse() |
Reverses elements in-place |
list1 = [1, 2]
list2 = [3, 4]
combined = list1 + list2
repeated = list1 * 3
nums = [40, 10, 50, 20, 10]
print("Count of 10:", nums.count(10))
print("Index of 50:", nums.index(50))
nums.sort()
print("Sorted Ascending:", nums)
nums.sort(reverse=True)
print("Sorted Descending:", nums)
Index of 50: 2
Sorted Ascending: [10, 10, 20, 40, 50]
Sorted Descending: [50, 40, 20, 10, 10]
Parts 24 - 27: Copying, Nested Lists & List Comprehension
What is List Comprehension?
List Comprehension provides a concise, readable one-liner syntax to create new lists based on existing iterables.
Syntax: [expression for item in iterable if condition]
Nested Lists Accessing
Nested list ke andar values ko access karne ke liye multiple square brackets use karte hain. Example: students[0][0] for first element of first row.
students = [["Gagan", 22], ["Rajat", 21]]
print("First student name:", students[0][0])
print("First student age:", students[0][1])
squares = [x ** 2 for x in range(1, 6)]
evens = [x for x in range(1, 11) if x % 2 == 0]
labels = ["Even" if x % 2 == 0 else "Odd" for x in range(1, 6)]
print("Squares:", squares)
print("Evens:", evens)
print("Labels:", labels)
First student age: 22
Squares: [1, 4, 9, 16, 25]
Evens: [2, 4, 6, 8, 10]
Labels: ['Odd', 'Even', 'Odd', 'Even', 'Odd']
Parts 28 - 35: Specific List Types, Unpacking & Math Built-ins
List Unpacking & * Operator
Assigning list items to individual variables directly: a, b, c = [10, 20, 30].
Using * to capture remaining items: first, *middle, last = [10, 20, 30, 40, 50].
Math & Boolean Functions
min(), max(), sum() Math calculations perform karte hain.
any(): Returns True if any item is True.
all(): Returns True only if all items are True.
nums = [10, 20, 30, 40, 50]
first, *middle, last = nums
print("First:", first)
print("Middle:", middle)
print("Last:", last)
print("Sum:", sum(nums))
print("Max:", max(nums))
print("Min:", min(nums))
print("Any True:", any([0, False, 5]))
print("All True:", all([1, True, 5]))
Middle: [20, 30, 40]
Last: 50
Sum: 150
Max: 50
Min: 10
Any True: True
All True: True
Parts 36 - 41: filter, zip, enumerate & Function Integration
| Function | Syntax | Use Case |
|---|---|---|
| filter() | list(filter(func, iterable)) |
Filters items based on condition function returning True |
| zip() | list(zip(l1, l2)) |
Pairs corresponding elements from multiple lists |
| enumerate() | enumerate(iterable, start=0) |
Provides index and value pairs during iteration |
| *args Unpacking | func(*my_list) |
Unpacks list elements as separate function arguments |
numbers = [1, 2, 3, 4, 5, 6]
evens = list(filter(lambda x: x % 2 == 0, numbers))
names = ["Aman", "Rahul", "Simran"]
marks = [80, 90, 85]
paired = list(zip(names, marks))
print("Filtered Evens:", evens)
print("Paired Data:", paired)
for index, name in enumerate(names, start=1):
print("Rank", index, ":", name)
Paired Data: [('Aman', 80), ('Rahul', 90), ('Simran', 85)]
Rank 1 : Aman
Rank 2 : Rahul
Rank 3 : Simran
Parts 42 - 46: Shallow Copy, Deep Copy, Aliasing & Memory Architecture
Aliasing vs Shallow vs Deep Copy
Aliasing (b = a): Both variables refer to exact same memory object.
Shallow Copy (b = a.copy()): Creates new outer list, but inner nested lists are shared references.
Deep Copy (b = copy.deepcopy(a)): Creates completely independent copies of outer and nested objects.
Memory Concept & 'is' Operator
Python variables hold references to objects in memory. is operator checks if two variables point to the exact same memory address (id(a) == id(b)).
| Concept | Code Example | Same Memory Object? | Nested Items Shared? |
|---|---|---|---|
| Aliasing | b = a |
Yes (True) | Yes |
| Shallow Copy | b = a.copy() |
No (False) | Yes |
| Deep Copy | b = copy.deepcopy(a) |
No (False) | No (Independent) |
import copy
orig = [[1, 2], [3, 4]]
shallow = orig.copy()
deep = copy.deepcopy(orig)
shallow[0].append(99)
print("Original after shallow edit:", orig)
print("Shallow copy:", shallow)
deep[1].append(100)
print("Original after deep edit:", orig)
print("Deep copy:", deep)
Shallow copy: [[1, 2, 99], [3, 4]]
Original after deep edit: [[1, 2, 99], [3, 4]]
Deep copy: [[1, 2], [3, 4, 100]]
Parts 47 - 50: Common Errors, Practice Questions & Mini Project
Common List Errors & Causes
- IndexError: list index out of range: Attempting to access an index that doesn't exist (e.g.
[10, 20][5]). - ValueError: list.remove(x): x not in list: Calling
remove()on a item not present in list. - TypeError: unsupported operand types: Adding non-list types to list without list conversion (e.g.
[1, 2] + 5). - AttributeError: 'list' object has no attribute 'upper': Calling string methods on list object directly.
10 Quick Practice Questions & Answers
nums = [10, 50, 20, 80, 30]
print("Q1 Largest:", max(nums))
print("Q2 Evens:", [x for x in nums if x % 2 == 0])
dups = [1, 2, 2, 3, 4, 4, 5]
unique = list(set(dups))
print("Q3 Unique:", unique)
print("Q4 Squares:", [x**2 for x in range(1, 6)])
unique_sorted = sorted(list(set(nums)))
print("Q5 Second Largest:", unique_sorted[-2])
names = ["Aman", "Rahul", "Priyanka", "Raj"]
longest = max(names, key=len)
print("Q6 Longest Name:", longest)
Real-Life Mini Project: Shopping Cart System
products = ["Laptop", "Mouse", "Keyboard"]
prices = [50000, 1000, 2000]
print("------ SHOPPING CART ------")
for product, price in zip(products, prices):
print(product, "=", price)
total = sum(prices)
discount = total * 0.10 if total >= 50000 else 0
final_price = total - discount
print("Total Price:", total)
print("Discount Applied:", discount)
print("Final Payable Amount:", final_price)
Laptop = 50000
Mouse = 1000
Keyboard = 2000
Total Price: 53000
Discount Applied: 5300.0
Final Payable Amount: 47700.0