CHAPTER 9 · DATA STRUCTURES

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.

English + Hinglish58 min readOnline practice included

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.

list-basic.pyPython
courses = ["HTML", "CSS", "Python"]
print(courses)
print(type(courses))
Hinglish Explanation

Square brackets [] ke andar comma-separated values likhkar list bana sakte ho. Order preserve hota hai, duplicates allowed hain, aur list mutable hoti hai.

Try a list →

Create lists

create.pyPython
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:

constructor.pyPython
letters = list("Python")
print(letters)

Indexing

List indexing zero se start hoti hai. Negative indexes end se count karte hain.

indexing.pyPython
colors = ["red", "green", "blue", "black"]

print(colors[0])   # red
print(colors[2])   # blue
print(colors[-1])  # black
print(colors[-2])  # blue
IndexError: Existing range ke bahar index access karoge to IndexError raise hota hai.

Slicing

List slicing syntax list[start:stop:step] hai. stop index exclude hota hai.

slicing.pyPython
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.

mutable.pyPython
skills = ["HTML", "CSS", "JS"]
skills[2] = "JavaScript"

print(skills)

Slice assignment bhi multiple elements replace kar sakti hai:

slice-assignment.pyPython
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.

append-extend.pyPython
skills = ["HTML", "CSS"]

skills.append("JavaScript")
print(skills)

skills.extend(["Python", "SQL"])
print(skills)
Difference: 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.

insert.pyPython
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.

remove.pyPython
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 par ValueError.
  • pop(index) removed value return karta hai; index optional hai.
  • del index ya slice delete kar sakta hai.
  • clear() list ko empty karta hai.

Membership and length

membership.pyPython
courses = ["Python", "Java", "C++"]

print(len(courses))
print("Python" in courses)
print("Go" not in courses)

index() and count()

index-count.pyPython
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.

sorting.pyPython
scores = [55, 92, 71, 88]

ascending = sorted(scores)
print(scores)
print(ascending)

scores.sort(reverse=True)
print(scores)
Important: 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()

reverse.pyPython
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.

copying.pyPython
original = [10, 20, 30]
alias = original
copy_a = original.copy()
copy_b = original[:]

alias.append(40)
print(original)  # changed
print(copy_a)    # unchanged

copy() 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.

nested.pyPython
matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

print(matrix[0])
print(matrix[1][2])
Shallow-copy caution: Nested structures copy karte waqt outer list copy hone ke baad bhi inner lists shared ho sakti hain. Deep copying later advanced usage me relevant hoti hai.

Loop through a list

iterate.pyPython
courses = ["HTML", "CSS", "Python"]

for course in courses:
    print(course)

Index bhi chahiye ho to enumerate() readable option hai:

enumerate.pyPython
courses = ["HTML", "CSS", "Python"]

for index, course in enumerate(courses, start=1):
    print(index, course)

Useful built-ins with numeric lists

aggregates.pyPython
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

unpacking.pyPython
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.

preview.pyPython
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.

safe-filter.pyPython
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.pyPython
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")

Run marks example →

Common beginner mistakes

  • Indexing ko 1 se start samajhna.
  • Out-of-range index access karna.
  • append() aur extend() 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 = original ko 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() vs extend() 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() vs sorted() 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.

  1. Empty marks list banao.
  2. Five marks user input se lo.
  3. Only 0–100 valid marks list me append karo.
  4. Valid marks print karo.
  5. Total calculate karo.
  6. Average calculate karo.
  7. Highest and lowest mark show karo.
  8. Passing marks 40+ count karo.
  9. Marks ko ascending order me new list ke through show karo.
  10. Original marks list preserve rakho.
  11. enumerate() se subject number + mark print karo.
  12. At least one membership test use karo.
  13. Empty-list case handle karo.
  14. One deliberate aliasing example test karke difference observe karo.

Open practice starter →