दिन 5: Lists, Tuples, Dictionaries और Sets
✅ आज आप सीखेंगे
- Lists: index, slice, जोड़ना, हटाना, sort
- Fixed records के लिए tuples
- Dictionaries: key → value lookup
- Unique values के लिए sets
- Dictionaries की list – असली data का आकार
🏢 असली दुनिया में
Delivery app की API orders को JSON में देती है – dictionaries की list, जैसे {"order_id": 101, "city": "Pune", "amount": 450}। pandas से पहले आपको ठीक इसी structure को पढ़ना और summarise करना आना चाहिए।
चार containers एक नज़र में
| Type | Syntax | Ordered | बदल सकते | Duplicates | किसलिए |
|---|---|---|---|---|---|
| list | [1, 2, 3] | हाँ | हाँ | हाँ | Values का एक column |
| tuple | (1, 2) | हाँ | नहीं | हाँ | Fixed record, जैसे (lat, lon) |
| dict | {"a": 1} | हाँ* | हाँ | Keys unique | Lookup, एक record |
| set | {1, 2} | नहीं | हाँ | नहीं | Unique values, membership |
Lists
orders = [1499, 299, 15999, 649, 2499] print(orders[0], orders[-1]) # first, last print(orders[1:4]) # slice: index 1, 2, 3 print(orders[:2], orders[-2:]) # first two, last two orders.append(899) # add at end orders.insert(0, 120) # add at position 0 orders.remove(299) # remove a value print(orders, len(orders)) print(sorted(orders), sorted(orders, reverse=True)[:3]) print(sum(orders), max(orders), min(orders))
Tuples – records जो बदलने नहीं चाहिए
office = ("Bengaluru", 12.9716, 77.5946) # city, latitude, longitude
city, lat, lon = office # unpacking
print(city, lat, lon)
try:
office[0] = "Mysuru"
except TypeError as e:
print("Tuples cannot change:", e)Dictionaries – key → value
student = {"name": "Priya", "class": 12, "marks": [95, 97, 91]}
print(student["name"], student.get("city", "not given"))
student["city"] = "Jaipur" # add / update
student["class"] = "12-A"
print(student)
print(list(student.keys()))
for key, value in student.items():
print(f"{key:6} -> {value}")gst_rate = {"Grocery": 5, "Fashion": 12, "Electronics": 18, "Books": 0}
cart = [("Atta 10kg", "Grocery", 459), ("Earbuds", "Electronics", 1499), ("Kurta", "Fashion", 899)]
for item, cat, price in cart:
rate = gst_rate[cat]
print(f"{item:10} {cat:12} ₹{price:5} + {rate:2}% = ₹{price * (1 + rate / 100):,.2f}")Sets – unique values
visitors_mon = {"u1", "u2", "u3", "u5"}
visitors_tue = {"u2", "u3", "u4"}
print("Unique cities:", sorted(set(["Pune", "Delhi", "Pune", "Agra", "Delhi"])))
print("Both days :", sorted(visitors_mon & visitors_tue)) # sorted() = fixed order
print("Any day :", sorted(visitors_mon | visitors_tue))
print("Only Monday :", sorted(visitors_mon - visitors_tue))
print("u4" in visitors_mon)Set print करने पर हर बार items अलग क्रम में दिख सकते हैं। Stable और readable क्रम चाहिए तो sorted() में लपेटें।
Dictionaries की list: असली data का आकार
orders = [
{"id": 101, "city": "Pune", "category": "Grocery", "amount": 450},
{"id": 102, "city": "Delhi", "category": "Electronics", "amount": 15999},
{"id": 103, "city": "Pune", "category": "Fashion", "amount": 1299},
{"id": 104, "city": "Mumbai", "category": "Grocery", "amount": 780},
{"id": 105, "city": "Delhi", "category": "Grocery", "amount": 320},
]
city_total = {}
for o in orders:
city_total[o["city"]] = city_total.get(o["city"], 0) + o["amount"]
print(city_total)
big = [o["id"] for o in orders if o["amount"] > 1000]
print("Big orders:", big)
top = max(orders, key=lambda o: o["amount"])
print("Top order:", top["id"], top["city"], top["amount"])from collections import Counter categories = ["Grocery", "Electronics", "Fashion", "Grocery", "Grocery", "Fashion"] c = Counter(categories) print(c) print(c.most_common(2))
एक जैसी keys वाली dictionaries की list एक table है: हर dict एक row और हर key एक column। Day 10 पर आप इसे एक line में pandas DataFrame बनाएँगे: pd.DataFrame(orders)।
Copy का जाल
a = [10, 20, 30] b = a # same list, two names! b.append(40) print(a) c = a.copy() # real copy c.append(50) print(a, c)
🏅 आज के Job Skills
Practice tasks
🏋️ Practice – ख़ुद करें
marks = [56, 78, 91, 45, 88, 67] से top 3 marks और बाकी का average print करें।Solution देखें
marks = [56, 78, 91, 45, 88, 67]
s = sorted(marks, reverse=True)
print("Top 3:", s[:3], "| rest avg:", sum(s[3:]) / len(s[3:]))orders list से हर category का total amount निकालें।Solution देखें
orders = [{"category": "Grocery", "amount": 450}, {"category": "Electronics", "amount": 15999},
{"category": "Fashion", "amount": 1299}, {"category": "Grocery", "amount": 780}, {"category": "Grocery", "amount": 320}]
total = {}
for o in orders:
total[o["category"]] = total.get(o["category"], 0) + o["amount"]
print(total)Solution देखें
a = {"Aman", "Priya", "Rahul", "Sneha"}
b = {"Priya", "Kabir", "Sneha"}
print("Both:", sorted(a & b))
print("Only one:", sorted(a ^ b))Quick quiz
🧠 Quick Quiz – ख़ुद को जाँचें
Interview corner
💼 Interview Corner
List vs tuple – कब कौन सा?
बढ़ने या बदलने वाले collection (values का column) के लिए list। Position से मतलब रखने वाले fixed record, जैसे coordinates या (key, value), के लिए tuple; tuples dictionary keys भी बन सकते हैं।
List की तुलना में set में membership check तेज़ क्यों है?
Set hash table इस्तेमाल करता है, इसलिए "x in s" size से लगभग स्वतंत्र समय लेता है (औसतन O(1))। List को item-by-item scan करना पड़ता है (O(n))।
सारांश
- list = ordered, बदलने योग्य values का column; [start:stop] से slice।
- tuple = fixed record; dict = key → value lookup; set = unique values।
- Dicts की list एक table है – pandas तक का पुल।
- अलग copy चाहिए तो .copy() लिखें।
Day 6: CSV और JSON files पढ़ना-लिखना, errors संभालना और Python modules इस्तेमाल करना।
