Lesson 5: Python Collections – Lists, Tuples, Sets & Dictionaries

Python Collections – Lists, Tuples, Sets & Dictionaries

Bro, ek baat bolu? Jab main pehli baar Python sikhta tha na, mujhe laga ye “collections” kuch museum jaisa topic hoga 😅 But bhai, ye toh Python ka asli backbone nikla. Data handle karne ka full system! Yahan tu sikhega kaise list, tuple, set aur dictionary ke saath data ko samjhe, modify kare aur control me rakhe — jaise ek pro developer.


Lists – Sabse Flexible Dost 🧩

List literally Python ka Swiss Army Knife hai. Matlab har jagah kaam aayegi — data store karne se lekar loops me ghusne tak. Dekho ek chhoti si list:

numbers = [10, 20, 30, 40]
names = ["Ritik", "Aman", "Simran"]
mix = [1, "Python", True, 3.14]

Dekha? Kuch bhi daal de bhai — int, string, float, sab mix ho sakta hai.

Accessing & Slicing

Jaise tu Netflix me specific episode choose karta hai, waise hi list ke elements bhi select kar sakta hai.

print(names[0])   # Ritik
print(names[-1])  # Simran
print(numbers[1:3])  # [20, 30]

Simple rule — indexing 0 se start hoti hai. Aur slicing likhne ka maza alag hi hai 😎

List Methods

Ab bro, list ke paas kuch secret moves hain:

  • append() – naya item add kar do end me.
  • insert() – specific jagah par item ghusa do.
  • remove() – item uda do.
  • sort() – list ko arrange kar do nicely.
  • reverse() – list ko ulti kar do 😂.
fruits = ["mango", "apple", "banana"]
fruits.append("grapes")
fruits.sort()
print(fruits)

Bas itna yaad rakh bro — list mutable hoti hai. Matlab tu isko badal sakta hai jitni baar chahe. Jaise exam ke baad marks list — kabhi na kabhi update hoti hi hai 😜


Tuples – The Unchangeable Bros 🔒

Ab aate hain tuples pe. Ye list jaisa hi lagta hai, bas ek chhoti si twist — ye change nahi hota. Matlab ek baar bana diya, fir usme kuch modify nahi kar sakta. Thoda stubborn type ka data structure hai 😆

t = (1, 2, 3, 4)
print(t[0])   # 1

Tuples ka use tab hota hai jab tu data safe rakhna chahta hai, jo galti se bhi modify na ho. Jaise fixed coordinates (x, y) ya week days.

days = ("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun")

Ye “days” kabhi badalne nahi chahiye, right? That’s why tuple perfect hai.


Sets – Unique Banda 🧠

Set basically wo banda hai jo sabse alag hona chahta hai. Kyuki bhai, set me duplicate elements allowed nahi hote. Bas unique items only!

nums = {1, 2, 3, 3, 4, 5}
print(nums)   # {1, 2, 3, 4, 5}

Duplicate gaya bhaad me 😎 Python automatically remove kar deta hai.

Set Operations

Ab ye hi part thoda mazedaar hai. Tu maths ke intersection, union yaad hai na? Bas wahi same yahan bhi hota hai:

a = {1, 2, 3, 4}
b = {3, 4, 5, 6}

print(a | b)  # Union → {1, 2, 3, 4, 5, 6}
print(a & b)  # Intersection → {3, 4}
print(a - b)  # Difference → {1, 2}

Set ke saath tu data compare kar sakta hai easily, specially jab tu duplicates se pareshaan ho.


Dictionaries – The Smartest of All 🧭

Ab bhai sabse intelligent collection — Dictionary. Isme tu data ko key-value pairs me store karta hai. Jaise ek mini database.

student = {
    "name": "Ritik",
    "age": 21,
    "course": "Python"
}

print(student["name"])  # Ritik

Dekha? Key likh ke value nikal li. Simple aur powerful.

Common Dictionary Methods

  • keys() – saare keys dikha dega.
  • values() – saare values dikhayega.
  • items() – dono ek saath tuple form me.
  • update() – new data add/update kar do.
  • pop() – kisi ek key-value pair ko remove kar do.
student["grade"] = "A"
print(student.keys())
print(student.values())

Dictionary mutable hai — matlab tu add/remove freely kar sakta hai. Ye structure web APIs, JSON data, aur config files me sabse zyada use hota hai.


Mini Project Time 🧠 – Contact Book

Ab thoda practical karte hain bro. Let’s build a tiny contact book jisme user naam aur number save karega. Simple project, but solid practice milegi.

contacts = {}

while True:
    print("\n1. Add Contact")
    print("2. View Contacts")
    print("3. Search Contact")
    print("4. Exit")

    choice = input("Enter choice: ")

    if choice == "1":
        name = input("Enter name: ")
        phone = input("Enter number: ")
        contacts[name] = phone
        print("Contact saved!")

    elif choice == "2":
        for name, number in contacts.items():
            print(f"{name}: {number}")

    elif choice == "3":
        search = input("Enter name to search: ")
        if search in contacts:
            print(f"{search}: {contacts[search]}")
        else:
            print("Contact not found.")

    elif choice == "4":
        print("Goodbye bro 👋")
        break

    else:
        print("Invalid choice, try again!")

Dekha? Bas dictionary ka magic aur thoda logic. Ye chhoti si script real-life use ke laayak hai. Tu ise file save karke future me aur upgrade bhi kar sakta hai (like adding delete or edit feature).


Bro-to-Bro Gyaan 💬

Bro, collections basically tere data ke dost hain. Har ek ka apna personality hai — List chill hai, Tuple serious, Set alag hi duniya ka banda hai, aur Dictionary? Smartest one.

Jab tu in sab ka feel samajh lega, Python tere liye khel ban jaayegi. Main bhi pehle confuse hota tha ki kab list use karu aur kab dict. But once tu thoda practice karega — sab natural ho jaayega.

Pro tip: Thoda experiments kar. Ek list ko set bana, ek set ko tuple bana, aur dekh kya hota hai. Python ko explore karne ka fun wahi hai.


Next Steps 🚀

  • Ek Word Counter bana — user se sentence lo aur har word ka count dikhao.
  • Next blog me hum karenge Functions & Modules — jahan tu apna code tod ke reusable parts banayega.

Tab tak practice kar bhai, aur yaad rakh — code likhne se better koi seekhne ka tareeka nahi 💻❤️

— Python + Coffee = Code ☕🐍

Post a Comment

0 Comments