Python Lists
List Python ki most-used built-in data structures me se ek hai. Is chapter me list creation, indexing, slicing, mutability, methods, sorting, copying, nested lists aur practical iteration patterns ko step by step samjhenge.
What is a list?
A list is an ordered, mutable collection. Ek list multiple values ko sequence me store karti hai aur uske elements ko baad me change kiya ja sakta hai.
courses = ["HTML", "CSS", "Python"]
print(courses)
print(type(courses))Square brackets [] ke andar comma-separated values likhkar list bana sakte ho. Order preserve hota hai, duplicates allowed hain, aur list mutable hoti hai.
Create lists
empty = []
numbers = [10, 20, 30]
names = ["Aman", "Riya", "Kabir"]
mixed = [1, "Python", True, 3.5]
print(empty)
print(numbers)
print(mixed)Python technically mixed types allow karta hai, lekin practical code me same-purpose data ko consistent type me rakhna usually clearer hota hai.
list() constructor se bhi iterable ko list me convert kar sakte ho:
letters = list("Python")
print(letters)Indexing
List indexing zero se start hoti hai. Negative indexes end se count karte hain.
colors = ["red", "green", "blue", "black"]
print(colors[0]) # red
print(colors[2]) # blue
print(colors[-1]) # black
print(colors[-2]) # blueIndexError raise hota hai.Slicing
List slicing syntax list[start:stop:step] hai. stop index exclude hota hai.
nums = [0, 1, 2, 3, 4, 5]
print(nums[1:4])
print(nums[:3])
print(nums[3:])
print(nums[::2])
print(nums[::-1])Basic slicing usually new list create karti hai.
Lists are mutable
String ke unlike list items ko index ke through change kiya ja sakta hai.
skills = ["HTML", "CSS", "JS"]
skills[2] = "JavaScript"
print(skills)Slice assignment bhi multiple elements replace kar sakti hai:
items = [1, 2, 3, 4]
items[1:3] = [20, 30, 40]
print(items)append() vs extend()
append() one object ko single item ki tarah end me add karta hai. extend() iterable ke elements ko individually add karta hai.
skills = ["HTML", "CSS"]
skills.append("JavaScript")
print(skills)
skills.extend(["Python", "SQL"])
print(skills)append(["Python", "SQL"]) nested list add karega, while extend(...) dono strings as separate elements add karega.insert()
insert(index, value) specified position par item add karta hai.
topics = ["Variables", "Loops"]
topics.insert(1, "Conditions")
print(topics)Middle insertion large lists me shifting cost create kar sakti hai; beginner code me readability pe focus rakho.
Remove items
Different situations ke liye different tools hain.
items = ["pen", "book", "bag", "book"]
items.remove("book") # first matching value
last = items.pop() # remove and return last item
first = items.pop(0) # remove and return index 0
del items[0] # delete by index
print(items, last, first)remove(value)first matching value remove karta hai; missing value parValueError.pop(index)removed value return karta hai; index optional hai.delindex ya slice delete kar sakta hai.clear()list ko empty karta hai.
Membership and length
courses = ["Python", "Java", "C++"]
print(len(courses))
print("Python" in courses)
print("Go" not in courses)index() and count()
marks = [80, 90, 80, 70]
print(marks.index(90))
print(marks.count(80))index() first matching position return karta hai; missing value par ValueError.
sort() and sorted()
list.sort() original list ko mutate karta hai. sorted() new sorted list return karta hai.
scores = [55, 92, 71, 88]
ascending = sorted(scores)
print(scores)
print(ascending)
scores.sort(reverse=True)
print(scores)scores.sort() ka return value None hota hai. Isliye scores = scores.sort() common mistake hai.Strings ko case-insensitive order me sort karne ke liye key=str.lower use kar sakte ho.
reverse()
numbers = [1, 2, 3, 4]
numbers.reverse()
print(numbers)reverse() original list mutate karta hai. Slicing numbers[::-1] new reversed list bana sakti hai.
Copying lists vs aliasing
Assignment se new independent list nahi banti; dono names same object ko reference kar sakte hain.
original = [10, 20, 30]
alias = original
copy_a = original.copy()
copy_b = original[:]
alias.append(40)
print(original) # changed
print(copy_a) # unchangedcopy() and slicing shallow copies hain. Nested mutable objects ke case me inner objects shared ho sakte hain.
Nested lists
List ke andar another list store kar sakte ho.
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
print(matrix[0])
print(matrix[1][2])Loop through a list
courses = ["HTML", "CSS", "Python"]
for course in courses:
print(course)Index bhi chahiye ho to enumerate() readable option hai:
courses = ["HTML", "CSS", "Python"]
for index, course in enumerate(courses, start=1):
print(index, course)Useful built-ins with numeric lists
marks = [78, 88, 92, 69]
print(sum(marks))
print(min(marks))
print(max(marks))
print(sum(marks) / len(marks))Empty list par average nikalne se pehle length check karna useful hai, otherwise division by zero ho sakta hai.
Basic list unpacking
point = [10, 20]
x, y = point
print(x, y)
values = [1, 2, 3, 4, 5]
first, *middle, last = values
print(first, middle, last)Unpacking ka deeper use next data-structure chapters me aur clear hoga.
List comprehension — preview
Python list comprehensions concise transformations ke liye powerful syntax hain. Detailed treatment Chapter 19 me hoga.
squares = [number ** 2 for number in range(1, 6)]
print(squares)Readable loop ko sirf short code banane ke liye unnecessarily comprehension me convert mat karo.
Do not mutate carelessly while iterating
Same list ko iterate karte waqt items remove/add karna unexpected skips ya confusing behavior create kar sakta hai.
numbers = [1, 2, 3, 4, 5, 6]
kept = []
for number in numbers:
if number % 2 == 0:
kept.append(number)
print(kept)Filtering ke liye new list banana often clearer beginner pattern hai.
Practical list workflow
marks = []
for _ in range(5):
mark = float(input("Enter mark: "))
if 0 <= mark <= 100:
marks.append(mark)
if marks:
print(f"Count: {len(marks)}")
print(f"Average: {sum(marks) / len(marks):.2f}")
print(f"Highest: {max(marks)}")
print(f"Lowest: {min(marks)}")
else:
print("No valid marks")Common beginner mistakes
- Indexing ko 1 se start samajhna.
- Out-of-range index access karna.
append()aurextend()ko confuse karna.list.sort()ko new list return karne wala function samajhna.remove()ko index-based removal samajhna.pop()ka returned value ignore karna jab needed ho.alias = originalko independent copy samajhna.- Nested lists me shallow-copy sharing ko ignore karna.
- Same list ko iterate karte waqt careless mutation karna.
- Empty list par average calculate karke division by zero create karna.
- Mixed unrelated data ko single list me rakhkar structure unclear banana.
Beginner best practices
- List ka purpose clear rakho aur meaningful variable names use karo.
- Value add karne ke intent ke basis par
append()vsextend()choose karo. - Original data preserve karna ho to
sorted()ya explicit copy use karo. - List empty ho sakti ho to calculations se pehle check karo.
- Index ki jagah direct iteration prefer karo jab index needed na ho.
- Index bhi chahiye ho to
enumerate()use karo. - Mutating methods ke return value ke assumptions verify karo.
- Nested mutable data copy karte waqt shallow-copy behavior samjho.
Chapter checklist
- List create, read and update kar sakte ho?
- Positive/negative indexing and slicing clear hai?
append(),extend(),insert()ka difference samajh aaya?remove(),pop(),del,clear()use kar sakte ho?sort()vssorted()ka difference clear hai?- Aliasing vs copying samajh aaya?
- Nested list access kar sakte ho?
- Loop aur
enumerate()se list process kar sakte ho?
Practice Task — Student Marks Analyzer
BrounStack Playground me list-based marks analyzer banao.
- Empty
markslist banao. - Five marks user input se lo.
- Only 0–100 valid marks list me append karo.
- Valid marks print karo.
- Total calculate karo.
- Average calculate karo.
- Highest and lowest mark show karo.
- Passing marks 40+ count karo.
- Marks ko ascending order me new list ke through show karo.
- Original marks list preserve rakho.
enumerate()se subject number + mark print karo.- At least one membership test use karo.
- Empty-list case handle karo.
- One deliberate aliasing example test karke difference observe karo.