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:

my_list = [10, 20, 30, "hello", 5.5]

Access Karna:

print(my_list[0]) # 10
print(my_list[3]) # hello
10
hello

2. append() Method

Meaning: append() ka matlab list ke end me ek naya element add karna.

Syntax:

list_name.append(element)

Correct Example:

fruits = ["apple", "banana"]
fruits.append("mango")
print(fruits)
['apple', 'banana', 'mango']

Galat Example:

fruits = ["apple"]
fruits.append("banana", "mango") # ❌ append sirf ek item le sakta hai

3. insert() Method

Meaning: Kisi specific position par item insert karna.

Syntax:

list_name.insert(index, element)
fruits = ["apple", "mango"]
fruits.insert(1, "banana")
print(fruits)
['apple', 'banana', 'mango']

4. remove() Method

Meaning: List me se koi specific item (value) ko hataana.

Syntax:

list_name.remove(value)
fruits = ["apple", "banana", "mango"]
fruits.remove("banana")
print(fruits)
['apple', 'mango']

Common Mistake:

fruits.remove("orange") # ❌ ValueError: orange list me hai hi nahi

5. pop() Method

Meaning: List se item nikaalo aur return bhi karo. Default last item ko pop karta hai.

Syntax:

item = list_name.pop() # last item
item = list_name.pop(index) # specific index
nums = [10, 20, 30]
x = nums.pop()
print(x)
print(nums)
30
[10, 20]

6. sort() Method

Meaning: List ko ascending (ya descending) order me arrange karna.

Syntax:

list_name.sort() # ascending
list_name.sort(reverse=True) # descending
nums = [5, 2, 9, 1]
nums.sort()
print(nums)
[1, 2, 5, 9]

Descending:

nums.sort(reverse=True)
print(nums)
[9, 5, 2, 1]

7. Summary Table of List Methods

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:

my_tuple = (10, 20, 30)
empty_tuple = ()
one_item_tuple = (5,) # Note: comma zaroori hai

Access Karna (Indexing):

print(my_tuple[0])
print(my_tuple[2])
10
30

Tuple Immutability Example:

my_tuple[1] = 50 # ❌ TypeError: 'tuple' object does not support item assignment

Tuple ke Saath Looping:

for item in my_tuple:
    print(item)
10
20
30

Why Use Tuples?

Common Mistake:

one_item = (5) # ❌ This is int, not tuple
print(type(one_item)) # Output: <class 'int'>

Correct Way:

one_item = (5,)
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:

my_set = {1, 2, 3, 4}
mixed_set = {"apple", 100, True}
empty_set = set() # ❌ {} likhne se empty dict banta hai

Set Me Duplicate Nahi Hota:

dup = {1, 2, 2, 3}
print(dup) # Output: {1, 2, 3}
{1, 2, 3}

Common Mistake (Indexing Try Karna):

my_set = {10, 20, 30}
print(my_set[0]) # ❌ Error: 'set' object is not subscriptable

Set me Values Add Karna - add():

s = {1, 2}
s.add(3)
print(s)
{1, 2, 3}

Remove vs Discard:

s = {1, 2, 3}
s.remove(2) # 2 hat gaya
s.discard(5) # 5 nahi tha, lekin error nahi aaya

Wrong Use of remove():

s = {1, 2, 3}
s.remove(5) # ❌ KeyError: 5 not found

Set Operations:

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

print(a.union(b)) # {1, 2, 3, 4, 5}
print(a.intersection(b)) # {3}
print(a.difference(b)) # {1, 2}
{1, 2, 3, 4, 5}
{3}
{1, 2}

Looping through Set:

for item in {"apple", "banana", "mango"}:
    print(item)

Important Notes:

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:

student = {
  "name": "Ravi",
  "age": 21,
  "grade": "A"
}
print(student["name"]) # Output: Ravi
Ravi

Empty Dictionary:

empty = {}
print(type(empty)) # Output: <class 'dict'>

Key-Value Access & Update:

student["age"] = 22 # value update
student["city"] = "Delhi" # new key-value add
print(student)
{'name': 'Ravi', 'age': 22, 'grade': 'A', 'city': 'Delhi'}

Access Karne ke Rules:

❌ Wrong Access:

student = {"name": "Amit"}
print(student["age"]) # ❌ Error: 'age' key nahi hai

✅ Safe Access with get():

print(student.get("age", "Not Found"))
print(student.get("name", "Not Found"))
Not Found
Amit

Important Methods:

Examples:

person = {"name": "Asha", "age": 30}
print(person.keys())
print(person.values())
print(person.items())
person.update({"city": "Mumbai"})
print(person)
person.pop("age")
print(person)
dict_keys(['name', 'age'])
dict_values(['Asha', 30])
dict_items([('name', 'Asha'), ('age', 30)])
{'name': 'Asha', 'age': 30, 'city': 'Mumbai'}
{'name': 'Asha', 'city': 'Mumbai'}

Looping Over Dictionary:

for key, value in person.items():
  print(key, "=>", value)
name => Asha
city => Mumbai

Note:

Nested Dictionary:

student = {
  "name": "Ravi",
  "marks": {"math": 90, "science": 95}
}
print(student["marks"]["science"]) # Output: 95