Free tutorials & notes in Hindi & English · Clean code examples 🧰 मुफ़्त PDF और फ़ोटो टूल्स →
🐍 Week 1 – Data Science के लिए Python  ·  दिन 05

दिन 5: Lists, Tuples, Dictionaries और Sets

⏱ 2 hours📶 Beginner🎯 100% self-study
दिन 5 / 60

✅ आज आप सीखेंगे

  • 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 एक नज़र में

TypeSyntaxOrderedबदल सकतेDuplicatesकिसलिए
list[1, 2, 3]हाँहाँहाँValues का एक column
tuple(1, 2)हाँनहींहाँFixed record, जैसे (lat, lon)
dict{"a": 1}हाँ*हाँKeys uniqueLookup, एक record
set{1, 2}नहींहाँनहींUnique values, membership

Lists

orders →14990-52991-4159992-36493-224994-1
बाएँ से positive index, दाएँ से negative
Python
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))
1499 2499 [299, 15999, 649] [1499, 299] [649, 2499] [120, 1499, 15999, 649, 2499, 899] 6 [120, 649, 899, 1499, 2499, 15999] [15999, 2499, 1499] 21665 15999 120

Tuples – records जो बदलने नहीं चाहिए

Python
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)
Bengaluru 12.9716 77.5946 Tuples cannot change: 'tuple' object does not support item assignment

Dictionaries – key → value

Python
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}")
Priya not given {'name': 'Priya', 'class': '12-A', 'marks': [95, 97, 91], 'city': 'Jaipur'} ['name', 'class', 'marks', 'city'] name -> Priya class -> 12-A marks -> [95, 97, 91] city -> Jaipur
Python
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}")
Atta 10kg Grocery ₹ 459 + 5% = ₹481.95 Earbuds Electronics ₹ 1499 + 18% = ₹1,768.82 Kurta Fashion ₹ 899 + 12% = ₹1,006.88

Sets – unique values

Python
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)
Unique cities: ['Agra', 'Delhi', 'Pune'] Both days : ['u2', 'u3'] Any day : ['u1', 'u2', 'u3', 'u4', 'u5'] Only Monday : ['u1', 'u5'] False
MondayTuesday
लौटने वाले visitors = Monday ∩ Tuesday
ℹ️ Sets का कोई क्रम नहीं

Set print करने पर हर बार items अलग क्रम में दिख सकते हैं। Stable और readable क्रम चाहिए तो sorted() में लपेटें।

Dictionaries की list: असली data का आकार

Python
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"])
{'Pune': 1749, 'Delhi': 16319, 'Mumbai': 780} Big orders: [102, 103] Top order: 102 Delhi 15999
Python
from collections import Counter
categories = ["Grocery", "Electronics", "Fashion", "Grocery", "Grocery", "Fashion"]
c = Counter(categories)
print(c)
print(c.most_common(2))
Counter({'Grocery': 3, 'Fashion': 2, 'Electronics': 1}) [('Grocery', 3), ('Fashion', 2)]
💡 यही तो DataFrame है

एक जैसी keys वाली dictionaries की list एक table है: हर dict एक row और हर key एक column। Day 10 पर आप इसे एक line में pandas DataFrame बनाएँगे: pd.DataFrame(orders)।

Copy का जाल

Python
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)
[10, 20, 30, 40] [10, 20, 30, 40] [10, 20, 30, 40, 50]

🏅 आज के Job Skills

✔ Lists slice और sort करना✔ Records को dictionaries में रखना✔ Sets से unique और common values✔ Dictionaries की list को summarise करना

Practice tasks

🏋️ Practice – ख़ुद करें

Task 1: marks = [56, 78, 91, 45, 88, 67] से top 3 marks और बाकी का average print करें।
Solution देखें
Python
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:]))
Top 3: [91, 88, 78] | rest avg: 56.0
Task 2: ऊपर की orders list से हर category का total amount निकालें।
Solution देखें
Python
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)
{'Grocery': 1550, 'Electronics': 15999, 'Fashion': 1299}
Task 3: दो classes ने quiz दिया। Class A: Aman, Priya, Rahul, Sneha। Class B: Priya, Kabir, Sneha। दोनों में और सिर्फ़ एक में वाले students print करें।
Solution देखें
Python
a = {"Aman", "Priya", "Rahul", "Sneha"}
b = {"Priya", "Kabir", "Sneha"}
print("Both:", sorted(a & b))
print("Only one:", sorted(a ^ b))
Both: ['Priya', 'Sneha'] Only one: ['Aman', 'Kabir', 'Rahul']

Quick quiz

🧠 Quick Quiz – ख़ुद को जाँचें

1. orders[-1] क्या देता है?
Negative index अंत से गिनते हैं।
2. कौन सा container बनने के बाद बदल नहीं सकता?
Tuples immutable हैं।
3. d.get("x", 0) कब 0 देता है?
Key न हो तो get default देता है – KeyError नहीं।
4. set([1, 1, 2, 3, 3]) क्या है?
Set सिर्फ़ unique values रखता है।
5. b = a फिर b.append(9)। a का क्या होगा?
दोनों नाम एक ही list की ओर हैं; असली copy के लिए a.copy()।

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 इस्तेमाल करना।

अक्सर पूछे जाने वाले प्रश्न (FAQ)

क्या dictionaries ordered हैं?
हाँ, Python 3.7 से dictionaries insertion order रखती हैं।
Counter क्या है?
collections module का dictionary subclass जो गिनता है हर value कितनी बार आई – frequency tables के लिए बढ़िया।
क्या list में अलग-अलग types हो सकते हैं?
हाँ, पर data के काम में हर list में एक type रखें (जैसे हर column में एक type) ताकि गणना में errors न आएँ।
← Data Science (60 Days)
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

अगला topicदिन 6: Files, CSV, JSON, Errors और Modules आपकी प्रगति: 5 / 60 (8%) · Lesson 6 / 60 आगे बढ़ें →

यह lesson कैसा लगा?

आपकी राय से हम content और बेहतर बनाते हैं।

अपना review और सुझाव लिखें (वैकल्पिक)

Review approve होने के बाद आपका नाम और शहर इसके साथ public दिख सकते हैं। Email या phone न लिखें।

▶ CodingEasily on YouTube

Video से सीखें – आसान Hindi में

चुनी हुई video: RDBMS भाग 3 – Class XI Commerce IT

▶ Channel subscribe करें