Chapter 7: Python Data Structures
Python Lists,tuples,sets,dictionary: Banane se leke modify karne tak - with full understanding, rules, aur mistakes!
Python List - Basic Samajh
List ek ordered collection hoti hai jisme hum multiple items store kar sakte hain. Items kisi bhi type ke ho sakte hain - int, str, float, etc.
Banane ka Tarika:
Access Karna:
print(my_list[3]) # hello
hello
2. append() Method
Meaning: append() ka matlab list ke end me ek naya element add karna.
Syntax:
Correct Example:
fruits.append("mango")
print(fruits)
Galat Example:
fruits.append("banana", "mango") # ❌ append sirf ek item le sakta hai
3. insert() Method
Meaning: Kisi specific position par item insert karna.
Syntax:
fruits.insert(1, "banana")
print(fruits)
4. remove() Method
Meaning: List me se koi specific item (value) ko hataana.
Syntax:
fruits.remove("banana")
print(fruits)
Common Mistake:
5. pop() Method
Meaning: List se item nikaalo aur return bhi karo. Default last item ko pop karta hai.
Syntax:
item = list_name.pop(index) # specific index
x = nums.pop()
print(x)
print(nums)
[10, 20]
6. sort() Method
Meaning: List ko ascending (ya descending) order me arrange karna.
Syntax:
list_name.sort(reverse=True) # descending
nums.sort()
print(nums)
Descending:
print(nums)
7. Summary Table of List Methods
append(x)– List ke end me x add karta haiinsert(i, x)– Position i pe x insert karta hairemove(x)– First occurrence of x ko hataata haipop([i])– i-th element ko remove karta hai aur return karta haisort()– List ko sort karta hai (ascending by default)
Python Tuples - Samajh Aur Use
Tuple bhi ek ordered collection hota hai jaise list, lekin immutable hota hai. Iska matlab: banane ke baad usme koi change (add, remove, update) nahi kar sakte.
Tuple Banane ka Tarika:
empty_tuple = ()
one_item_tuple = (5,) # Note: comma zaroori hai
Access Karna (Indexing):
print(my_tuple[2])
30
Tuple Immutability Example:
Tuple ke Saath Looping:
print(item)
20
30
Why Use Tuples?
- Data ko fixed rakhna ho (jaise coordinates, config settings)
- Faster than list (thoda performance better hota hai)
- Can be used as dictionary keys (lists nahi ho sakte)
Common Mistake:
print(type(one_item)) # Output: <class 'int'>
Correct Way:
print(type(one_item)) # Output: <class 'tuple'>
Python Sets - Unordered Unique Collection
Set ek aisi collection hoti hai jisme unique elements hote hain. Iska order fixed nahi hota (unordered), aur indexing allowed nahi hai.
Set Banane ka Tarika:
mixed_set = {"apple", 100, True}
empty_set = set() # ❌ {} likhne se empty dict banta hai
Set Me Duplicate Nahi Hota:
print(dup) # Output: {1, 2, 3}
Common Mistake (Indexing Try Karna):
print(my_set[0]) # ❌ Error: 'set' object is not subscriptable
Set me Values Add Karna - add():
s.add(3)
print(s)
Remove vs Discard:
s.remove(2) # 2 hat gaya
s.discard(5) # 5 nahi tha, lekin error nahi aaya
Wrong Use of remove():
s.remove(5) # ❌ KeyError: 5 not found
Set Operations:
union()- Do sets ka combined resultintersection()- Common elementsdifference()- Jo ek set me hai dusre me nahi
b = {3, 4, 5}
print(a.union(b)) # {1, 2, 3, 4, 5}
print(a.intersection(b)) # {3}
print(a.difference(b)) # {1, 2}
{3}
{1, 2}
Looping through Set:
print(item)
Important Notes:
- Sets unordered hote hain — same order me print nahi hota
- Indexing, slicing allowed nahi hai
- Only immutable (unchangeable) elements allowed — list inside set ❌
Python Dictionaries - Key-Value Ka Magic
Dictionary ek aisa data structure hai jo key-value pairs me data store karta hai. Har key unique hoti hai, aur uske saath ek value jodi hoti hai.
Dictionary Banane ka Tarika:
"name": "Ravi",
"age": 21,
"grade": "A"
}
print(student["name"]) # Output: Ravi
Empty Dictionary:
print(type(empty)) # Output: <class 'dict'>
Key-Value Access & Update:
student["city"] = "Delhi" # new key-value add
print(student)
Access Karne ke Rules:
- Key case-sensitive hoti hai ("Name" ≠ "name")
- Agar key exist nahi karti aur access kiya to ❌
KeyErroraata hai
❌ Wrong Access:
print(student["age"]) # ❌ Error: 'age' key nahi hai
✅ Safe Access with get():
print(student.get("name", "Not Found"))
Amit
Important Methods:
get()– safely value access karta haikeys()– sabhi keys ka list deta haivalues()– sabhi values deta haiitems()– sabhi key-value pairs as tuples deta haiupdate()– ek dict me doosri dict ke items add/overwrite karta haipop()– kisi key ko hata kar uski value return karta hai
Examples:
print(person.keys())
print(person.values())
print(person.items())
person.update({"city": "Mumbai"})
print(person)
person.pop("age")
print(person)
dict_values(['Asha', 30])
dict_items([('name', 'Asha'), ('age', 30)])
{'name': 'Asha', 'age': 30, 'city': 'Mumbai'}
{'name': 'Asha', 'city': 'Mumbai'}
Looping Over Dictionary:
print(key, "=>", value)
city => Mumbai
Note:
- Keys unique hoti hain, values duplicate ho sakti hain
- Keys immutable types hi ho sakti hain (string, number, tuple)
- Nested dictionaries bhi possible hain
Nested Dictionary:
"name": "Ravi",
"marks": {"math": 90, "science": 95}
}
print(student["marks"]["science"]) # Output: 95
