इस chapter में हम Python के Sequence Data Types के बारे में सीखेंगे — Lists, Tuples और Dictionaries। इसमें Slicing, Indexing, Concatenation, Mutability जैसे concepts और कई उदाहरण जैसे maximum, minimum, mean निकालना, linear search और dictionary frequency count शामिल हैं।
Python में Sequence Data Types वे data structures हैं जिनमें कई items को एक ordered sequence में store किया जा सकता है। इनकी खासियत है कि हर element का एक index number होता है जिससे हम किसी भी value को access कर सकते हैं।
String, List, Tuple etc.
| Data Type | Mutable | Example | Description |
|---|---|---|---|
| String | No ❌ | "Hello" | Characters arranged in sequence |
| List | Yes ✅ | [1, 2, 3] | Ordered, changeable collection |
| Tuple | No ❌ | (1, 2, 3) | Ordered, unchangeable collection |
| Range | No ❌ | range(5) | Represents sequence of numbers |
हर sequence में items को उनकी index position से access किया जा सकता है। Index हमेशा 0 से शुरू होती है।
name = "PYTHON"
print(name[0]) # First character
print(name[3]) # Fourth character
Output:
numbers = [10, 20, 30, 40, 50]
print(numbers[-1]) # Last element
print(numbers[-3]) # Third from end
Output:Slicing से हम sequence का कोई हिस्सा निकाल सकते हैं:
list1 = [10, 20, 30, 40, 50, 60]
print(list1[1:4]) # index 1 to 3
print(list1[:3]) # start to index 2
print(list1[::2]) # every 2nd element
Output:
a = [1, 2, 3]
b = [4, 5]
print(a + b) # Concatenation
print(a * 2) # Repetition
Output:
fruits = ["apple", "banana", "cherry"]
for item in fruits:
print(item)
Output:| Operation | Meaning | Example | Output |
|---|---|---|---|
| len() | Length of sequence | len([1,2,3]) | 3 |
| max() | Maximum value | max([5,1,8]) | 8 |
| min() | Minimum value | min((2,9,4)) | 2 |
| sum() | Sum of all values | sum([2,4,6]) | 12 |
| in | Membership check | 2 in [1,2,3] | True |
marks = [78, 85, 90, 66, 88]
total = sum(marks)
avg = total / len(marks)
print("Average Marks =", avg)
Output:
Python में List एक Ordered, Mutable (changeable) collection होती है जिसमें हम कई elements एक साथ रख सकते हैं।
Lists को square brackets [ ] में लिखा जाता है।
यह Python में सबसे ज़्यादा इस्तेमाल होने वाला sequence data type है।
list_name = [element1, element2, element3, ...]
fruits = ["apple", "banana", "cherry"]
print(fruits)
Output:
['apple', 'banana', 'cherry']
empty_list = []
numbers = [1, 2, 3, 4]
mixed = [10, "Python", 3.14, True]
nested = [[1, 2, 3], [4, 5, 6]]
animals = ["cat", "dog", "elephant", "tiger"]
print(animals[0]) # first element
print(animals[-1]) # last element
Output:
cat
tiger
data = [10, 20, 30, 40, 50]
print(data[1:4]) # elements 1 to 3
print(data[:3]) # first three
print(data[::2]) # every second element
Output:
[20, 30, 40]
[10, 20, 30]
[10, 30, 50]
names = ["Amit", "Ravi", "Kiran"]
for name in names:
print("Hello", name)
Output:
Hello Amit
Hello Ravi
Hello Kiran
nums = [10, 20, 30]
nums[1] = 99
nums.append(40)
nums.insert(1, 15)
print(nums)
Output:
[10, 15, 99, 30, 40]
nums = [10, 20, 30, 40, 50]
nums.remove(30)
nums.pop(2)
del nums[0]
print(nums)
Output:
[40, 50]
| Method | Description | Example |
|---|---|---|
| append() | Add element at end | list.append(5) |
| insert() | Insert at specific position | list.insert(1, "Hi") |
| remove() | Remove specific element | list.remove(2) |
| pop() | Remove last element or by index | list.pop(2) |
| sort() | Sort list ascending | list.sort() |
| reverse() | Reverse list order | list.reverse() |
| copy() | Return shallow copy | list.copy() |
| clear() | Remove all elements | list.clear() |
a = [1, 2]
b = [3, 4]
print(a + b) # concatenation
print(a * 3) # repetition
Output:
[1, 2, 3, 4]
[1, 2, 1, 2, 1, 2]
nums = [10, 20, 30, 40, 50]
print(len(nums))
print(max(nums))
print(min(nums))
print(sum(nums))
Output:
5
50
10
150
colors = ["red", "green", "blue"]
print("red" in colors)
print("yellow" not in colors)
Output:
True
True
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
print(matrix[1][2])
Output:
6
nums = [12, 45, 23, 67, 34]
largest = max(nums)
print("Largest =", largest)
Output:
Largest = 67
nums = [1, 2, 3, 4, 5, 6, 7, 8]
even = 0
odd = 0
for n in nums:
if n % 2 == 0:
even += 1
else:
odd += 1
print("Even:", even)
print("Odd:", odd)
Output:
Even: 4
Odd: 4
nums = [10, 20, 30, 40]
rev = nums[::-1]
print(rev)
Output:
[40, 30, 20, 10]
data = [5, 10, 15, 20]
total = 0
for i in data:
total += i
print("Total =", total)
Output:
Total = 50
items = [1, 2, 2, 3, 4, 4, 5]
unique = []
for i in items:
if i not in unique:
unique.append(i)
print(unique)
Output:
[1, 2, 3, 4, 5]
nums = [1, 2, 3, 4, 5]
squares = [n * n for n in nums]
print(squares)
Output:
[1, 4, 9, 16, 25]
nums = [10, 40, 20, 50, 30]
nums.sort()
print("Second Largest =", nums[-2])
Output:
Second Largest = 40
nums = [2, 3, 4]
product = 1
for n in nums:
product *= n
print("Product =", product)
Output:
Product = 24
nums = [-3, 5, -1, 0, 7, -8]
pos = []
neg = []
for n in nums:
if n >= 0:
pos.append(n)
else:
neg.append(n)
print("Positive:", pos)
print("Negative:", neg)
Output:
Positive: [5, 0, 7]
Negative: [-3, -1, -8]
nums = [11, 12, 13, 14, 15, 16]
for i in nums:
if i % 2 == 0:
print(i)
Output:
12
14
16
Tuple Python का एक ordered and immutable (unchangeable) collection data type है।
Tuple को parentheses ( ) में लिखा जाता है।
यह list की तरह दिखता है लेकिन इसमें एक बार value assign करने के बाद उसे बदला नहीं जा सकता।
A tuple is an ordered collection of elements enclosed in parentheses ( )
and is immutable (cannot be changed after creation).
tuple_name = (element1, element2, element3, ...)
fruits = ("apple", "banana", "cherry")
print(fruits)
Output:
('apple', 'banana', 'cherry')
empty_tuple = ()
numbers = (1, 2, 3, 4)
mixed = (10, "Python", 3.14, True)
nested = ((1, 2), (3, 4))
single = (5,) # Must add comma for single element tuple
colors = ("red", "green", "blue", "yellow")
print(colors[0])
print(colors[-1])
Output:
red
yellow
nums = (10, 20, 30, 40, 50)
print(nums[1:4])
print(nums[:3])
print(nums[::-1]) # reversed
Output:
(20, 30, 40)
(10, 20, 30)
(50, 40, 30, 20, 10)
| Feature | List | Tuple |
|---|---|---|
| Definition | Ordered, mutable collection | Ordered, immutable collection |
| Syntax | [ ] square brackets | ( ) parentheses |
| Mutability | Mutable | Immutable |
| Performance | Slower | Faster |
| Use Case | When data may change | When data should stay constant |
a = (1, 2, 3)
b = (4, 5)
print(a + b) # concatenation
print(a * 2) # repetition
Output:
(1, 2, 3, 4, 5)
(1, 2, 3, 1, 2, 3)
nums = (10, 20, 30, 40)
print(20 in nums)
print(50 not in nums)
Output:
True
True
nums = (10, 20, 30, 40, 50)
print(len(nums))
print(max(nums))
print(min(nums))
print(sum(nums))
Output:
5
50
10
150
| Method | Description | Example |
|---|---|---|
| count() | Returns number of occurrences of a value | t.count(2) |
| index() | Returns index of first occurrence | t.index(10) |
animals = ("dog", "cat", "horse")
for a in animals:
print(a)
Output:
dog
cat
horse
t = (1, 2, 3)
l = list(t) # tuple to list
l.append(4)
t2 = tuple(l)
print(t2)
Output:
(1, 2, 3, 4)
nums = (45, 12, 89, 33, 67)
print("Max:", max(nums))
print("Min:", min(nums))
Output:
Max: 89
Min: 12
t = (1, 2, 3, 2, 2, 4, 5)
print("2 appears", t.count(2), "times")
Output:
2 appears 3 times
t = (10, 20, 30, 40)
print("Index of 30:", t.index(30))
Output:
Index of 30: 2
cities = ("Delhi", "Mumbai", "Kolkata")
for i in range(len(cities)):
print(i, ":", cities[i])
Output:
0 : Delhi
1 : Mumbai
2 : Kolkata
colors = ("red", "blue", "green")
if "blue" in colors:
print("Yes, blue is present!")
Output:
Yes, blue is present!
student = ("Amit", 20, "Delhi")
name, age, city = student
print("Name:", name)
print("Age:", age)
print("City:", city)
Output:
Name: Amit
Age: 20
City: Delhi
t = ((1, 2), (3, 4), (5, 6))
print(t[1][0])
Output:
3
data = [("a", 1), ("b", 2), ("c", 3)]
d = dict(data)
print(d)
Output:
{'a': 1, 'b': 2, 'c': 3}
t = (1, 2, 3, 2, 4, 2, 5)
repeated = []
for i in t:
if t.count(i) > 1 and i not in repeated:
repeated.append(i)
print(repeated)
Output:
[2]
count() and index().
Python में Dictionary एक unordered, mutable, and key-value pair data type है।
यह real-world mapping (जैसे student → marks) को store करने के लिए use होता है।
Dictionary को curly braces { } में लिखा जाता है।
A dictionary is an unordered collection of key-value pairs where each key is unique.
Dictionaries are mutable and written in curly braces { }.
dict_name = {
key1: value1,
key2: value2,
key3: value3
}
student = {"name": "Amit", "age": 20, "course": "Python"}
print(student)
Output:
{'name': 'Amit', 'age': 20, 'course': 'Python'}
empty_dict = {}
student = {"name": "Ravi", "age": 18, "grade": "A"}
numbers = {1: "one", 2: "two", 3: "three"}
nested = {"person": {"name": "Amit", "age": 22}}
student = {"name": "Amit", "age": 20, "course": "Python"}
print(student["name"])
print(student.get("age"))
Output:
Amit
20
student = {"name": "Amit", "age": 20}
student["course"] = "Python"
student["age"] = 21
print(student)
Output:
{'name': 'Amit', 'age': 21, 'course': 'Python'}
student = {"name": "Amit", "age": 20, "course": "Python"}
student.pop("age") # removes key
del student["course"] # delete key
student.clear() # removes all
print(student)
Output:
{}
| Method | Description | Example |
|---|---|---|
| keys() | Returns list of keys | d.keys() |
| values() | Returns list of values | d.values() |
| items() | Returns key-value pairs | d.items() |
| get() | Returns value for a key | d.get('name') |
| pop() | Removes specific key | d.pop('age') |
| update() | Adds or updates key-value pairs | d.update({'grade': 'A'}) |
| clear() | Removes all items | d.clear() |
| copy() | Copies dictionary | d.copy() |
student = {"name": "Amit", "age": 20, "course": "Python"}
for key, value in student.items():
print(key, ":", value)
Output:
name : Amit
age : 20
course : Python
data = {"a": 1, "b": 2, "c": 3}
print(len(data))
print(max(data))
print(min(data))
print(str(data))
Output:
3
c
a
{'a': 1, 'b': 2, 'c': 3}
d1 = {"a": 1, "b": 2}
d2 = {"c": 3, "d": 4}
d1.update(d2)
print(d1)
Output:
{'a': 1, 'b': 2, 'c': 3, 'd': 4}
text = "banana"
freq = {}
for ch in text:
freq[ch] = freq.get(ch, 0) + 1
print(freq)
Output:
{'b': 1, 'a': 3, 'n': 2}
d1 = {"x": 10, "y": 20}
d2 = {"z": 30}
merged = {**d1, **d2}
print(merged)
Output:
{'x': 10, 'y': 20, 'z': 30}
data = {"a": 100, "b": 200, "c": 300}
print("Sum =", sum(data.values()))
Output:
Sum = 600
data = {"id": 1, "name": "Amit"}
if "id" in data:
print("Key found")
Output:
Key found
data = {"a": 10, "b": 25, "c": 15}
max_key = max(data, key=data.get)
print("Key with max value:", max_key)
Output:
Key with max value: b
keys = ["name", "age", "city"]
values = ["Ravi", 20, "Delhi"]
info = dict(zip(keys, values))
print(info)
Output:
{'name': 'Ravi', 'age': 20, 'city': 'Delhi'}
students = {
"101": {"name": "Amit", "age": 20},
"102": {"name": "Ravi", "age": 22}
}
print(students["102"]["name"])
Output:
Ravi
data = {"a": 1, "b": 2, "c": 1}
unique = {}
for k, v in data.items():
if v not in unique.values():
unique[k] = v
print(unique)
Output:
{'a': 1, 'b': 2}
data = {"a": 10, "b": 20, "c": 30}
swapped = {v: k for k, v in data.items()}
print(swapped)
Output:
{10: 'a', 20: 'b', 30: 'c'}
data = {"a": 5, "b": 15, "c": 25}
filtered = {k: v for k, v in data.items() if v > 10}
print(filtered)
Output:
{'b': 15, 'c': 25}
update() or unpacking operator {**d1, **d2}.Python में Set एक unordered, mutable collection है जो unique elements को store करता है। यानी set में कोई भी duplicate value नहीं होती। Set का use mathematical set operations जैसे Union, Intersection, Difference के लिए किया जाता है।
A set is an unordered collection of unique and immutable elements enclosed in curly braces { }.
set_name = {element1, element2, element3, ...}
fruits = {"apple", "banana", "cherry"}
print(fruits)
Output:
{'banana', 'cherry', 'apple'}
empty_set = set() # not {}
numbers = {1, 2, 3, 4}
mixed = {10, "Python", 3.14, True}
s = {10, 20, 30}
s.add(40) # Add one element
s.update([50, 60]) # Add multiple elements
s.remove(20) # Remove specific element
s.discard(100) # No error if not found
print(s)
Output:
{40, 10, 50, 30, 60}
| Method | Description | Example |
|---|---|---|
| add() | Adds an element | s.add(5) |
| update() | Adds multiple elements | s.update([1,2]) |
| remove() | Removes element; error if not found | s.remove(3) |
| discard() | Removes element; no error if missing | s.discard(10) |
| pop() | Removes random element | s.pop() |
| clear() | Removes all elements | s.clear() |
| copy() | Copies set | s.copy() |
A = {1, 2, 3, 4}
B = {3, 4, 5, 6}
print("Union:", A | B)
print("Intersection:", A & B)
print("Difference:", A - B)
print("Symmetric Difference:", A ^ B)
Output:
Union: {1, 2, 3, 4, 5, 6}
Intersection: {3, 4}
Difference: {1, 2}
Symmetric Difference: {1, 2, 5, 6}
colors = {"red", "green", "blue"}
print("red" in colors)
print("yellow" not in colors)
Output:
True
True
nums = {10, 20, 30, 40, 50}
print(len(nums))
print(max(nums))
print(min(nums))
print(sum(nums))
Output:
5
50
10
150
nums = [1, 2, 2, 3, 4, 4, 5]
unique = set(nums)
print(unique)
Output:
{1, 2, 3, 4, 5}
A = {1, 2, 3, 4}
B = {3, 5, 6, 2}
common = A & B
print("Common:", common)
Output:
Common: {2, 3}
A = {1, 2, 3, 4}
B = {3, 4, 5}
print(A - B)
Output:
{1, 2}
word = "programming"
vowels = {'a', 'e', 'i', 'o', 'u'}
result = set(word) & vowels
print(result)
Output:
{'a', 'i', 'o'}
sentence = "python is easy and python is powerful"
words = set(sentence.split())
print("Unique words:", len(words))
Output:
Unique words: 5
A = {1, 2, 3}
B = {1, 2, 3}
print(A == B)
Output:
True
A = {1, 2}
B = {1, 2, 3, 4}
print(A.issubset(B))
print(B.issuperset(A))
Output:
True
True
A = {1, 2, 3}
B = {3, 4, 5}
print(A ^ B)
Output:
{1, 2, 4, 5}
A = {10, 20, 30}
A.clear()
print(A)
Output:
set()
nums = [1, 2, 2, 3, 3, 4]
unique_list = list(set(nums))
print(unique_list)
Output:
[1, 2, 3, 4]
update() method.remove() gives error if element not found, discard() does not.Python में Indexing, Slicing, और Concatenation sequence data types (जैसे list, string, tuple) के साथ काम करने के लिए basic और powerful concepts हैं। इनका use data को access, extract और combine करने के लिए किया जाता है।
Indexing का मतलब होता है किसी sequence के element को उसकी position (index number) से access करना। Python में indexing 0 से शुरू होती है।
sequence[index]
name = "PYTHON"
print(name[0]) # First character
print(name[3]) # Fourth character
print(name[-1]) # Last character
Output:
P
H
N
fruits = ["apple", "banana", "cherry", "mango"]
print(fruits[1])
print(fruits[-2])
Output:
banana
cherry
Slicing का मतलब है किसी sequence का हिस्सा (subsequence) निकालना। यह तीन parameters पर आधारित होता है:
sequence[start : stop : step]
text = "PYTHON"
print(text[0:3]) # P, Y, T
print(text[2:5]) # T, H, O
print(text[:4]) # P, Y, T, H
print(text[2:]) # T, H, O, N
print(text[::-1]) # Reverse string
Output:
PYT
THO
PYTH
THON
NOHTYP
numbers = [10, 20, 30, 40, 50, 60]
print(numbers[1:4])
print(numbers[:3])
print(numbers[::2])
print(numbers[::-1])
Output:
[20, 30, 40]
[10, 20, 30]
[10, 30, 50]
[60, 50, 40, 30, 20, 10]
Concatenation का मतलब है दो या अधिक sequences को जोड़ना (combine करना)। Python में + operator से concatenation किया जाता है।
a = "Hello"
b = "World"
result = a + " " + b
print(result)
Output:
Hello World
list1 = [1, 2, 3]
list2 = [4, 5, 6]
merged = list1 + list2
print(merged)
Output:
[1, 2, 3, 4, 5, 6]
t1 = (10, 20)
t2 = (30, 40)
print(t1 + t2)
Output:
(10, 20, 30, 40)
data = "INFORMATION"
print(data[0:5]) # First 5 characters
print(data[-5:]) # Last 5 characters
print(data[::2]) # Every second character
print(data[::-2]) # Reverse skip 2 chars
Output:
INFOR
ATION
IFRMTN
NTROI
nums = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print(nums[::3])
print(nums[1:8:2])
print(nums[5:2:-1])
Output:
[1, 4, 7]
[2, 4, 6, 8]
[6, 5, 4]
text = "python"
rev = text[::-1]
print(rev)
Output:
nohtyp
word = "programming"
print(word[:3] + word[-3:])
Output:
proing
A = [1, 2, 3]
B = [4, 5, 6, 7]
merged = A + B
print(merged)
print("Total Length:", len(merged))
Output:
[1, 2, 3, 4, 5, 6, 7]
Total Length: 7
nums = [10, 20, 30, 40, 50, 60]
print(nums[:2] + nums[-2:])
Output:
[10, 20, 50, 60]
txt = "PYTHONPROGRAM"
print(txt[::2])
Output:
PTOPORM
boys = ("Amit", "Ravi")
girls = ("Neha", "Pooja")
students = boys + girls
print(students)
Output:
('Amit', 'Ravi', 'Neha', 'Pooja')
A = [10, 20, 30]
B = A[:]
print(B)
Output:
[10, 20, 30]
text = input("Enter a word: ")
print("First 3 letters:", text[:3])
print("Last 3 letters:", text[-3:])
Output:
Enter a word: Python
First 3 letters: Pyt
Last 3 letters: hon
nums = [1, 2, 3, 4, 5]
print(nums[::-1])
Output:
[5, 4, 3, 2, 1]
word = "madam"
if word == word[::-1]:
print("Palindrome")
else:
print("Not Palindrome")
Output:
Palindrome
+ operator joins two sequences of same type.Python में हर object (जैसे list, tuple, string, set, dictionary आदि) memory में एक reference के रूप में store होता है। Mutability यह बताती है कि कोई object memory में बदल सकता है या नहीं।
- Mutable → Changeable in place (same memory id)
- Immutable → Creates new object when changed
| Category | Data Type | Mutable? |
|---|---|---|
| Sequence | List | ✅ Mutable |
| Sequence | Tuple | 🚫 Immutable |
| Sequence | String | 🚫 Immutable |
| Mapping | Dictionary | ✅ Mutable |
| Set | Set | ✅ Mutable |
| Numeric | int, float, complex | 🚫 Immutable |
# Lists are mutable
fruits = ["apple", "banana", "cherry"]
print(id(fruits)) # memory id before change
fruits.append("mango")
print(fruits)
print(id(fruits)) # memory id remains same
Output:
2638412471552
['apple', 'banana', 'cherry', 'mango']
2638412471552 (same id → object modified in place)
# Strings are immutable
text = "Python"
print(id(text)) # before change
text = text + "3.11"
print(text)
print(id(text)) # new id created
Output:
1890314117296
Python3.11
1890314117360 (new id → new object created)
जब आप mutable object (जैसे list या dict) को modify करते हैं, Python उसी memory address पर changes करता है। लेकिन immutable object (जैसे string, tuple, int) को बदलने की कोशिश करने पर Python एक new object बनाता है।
a = 10
b = a
print(id(a), id(b)) # same id initially
b = b + 5
print(id(a), id(b)) # new id for b (immutable)
Output:
145231232
145231280 (b changes → new object created)
# List example
A = [1, 2, 3]
B = A
B.append(4)
print("A:", A)
print("B:", B)
# Tuple example
X = (1, 2, 3)
Y = X
Y = Y + (4,)
print("X:", X)
print("Y:", Y)
Output:
A: [1, 2, 3, 4]
B: [1, 2, 3, 4]
X: (1, 2, 3)
Y: (1, 2, 3, 4)
student = {"name": "Amit", "age": 20}
print(id(student))
student["age"] = 21
print(student)
print(id(student)) # same id (changed in place)
Output:
2168547857808
{'name': 'Amit', 'age': 21}
2168547857808 (same)
a = "Hello"
print(id(a))
a += " World"
print(id(a)) # new object (immutable)
b = [1, 2, 3]
print(id(b))
b.append(4)
print(id(b)) # same object (mutable)
Output:
Different id for string
Same id for list
L = [1, 2, 3]
print("Before:", L)
L[0] = 100
print("After:", L)
Output:
Before: [1, 2, 3]
After: [100, 2, 3]
s = "hello"
try:
s[0] = "H"
except TypeError as e:
print(e)
Output:
'str' object does not support item assignment
num = 5
print(id(num))
num += 1
print(id(num))
Output:
Different ids → immutable
data = {"x": 10, "y": 20}
data["z"] = 30
print(data)
Output:
{'x': 10, 'y': 20, 'z': 30}
t = (1, 2, 3)
try:
t[1] = 99
except TypeError:
print("Tuple is immutable")
Output:
Tuple is immutable
id() before and after modification.id() function.
Lists mutable होते हैं — यानी इनकी values बदलने पर object का id() नहीं बदलता।
numbers = [10, 20, 30]
print("Before:", numbers)
print("Memory ID:", id(numbers))
numbers.append(40)
print("After:", numbers)
print("Memory ID:", id(numbers)) # Same ID
Output:
Before: [10, 20, 30]
After: [10, 20, 30, 40]
Same memory id → Mutable
Strings immutable होते हैं — किसी भी परिवर्तन से नया object बनता है।
text = "Python"
print("Before ID:", id(text))
text += "3.11"
print("After ID:", id(text))
Output:
Different IDs → Immutable
Dictionaries mutable होते हैं — नए key-value pair जोड़ने पर भी id वही रहती है।
student = {"name": "Amit", "age": 20}
print("Before ID:", id(student))
student["grade"] = "A"
print(student)
print("After ID:", id(student))
Output:
Same ID → Dictionary is mutable
Tuple के elements को बदला नहीं जा सकता — कोशिश करने पर error आता है।
data = (1, 2, 3)
try:
data[0] = 99
except TypeError as e:
print(e)
Output:
'tuple' object does not support item assignment
Tuple immutable होता है, लेकिन अगर उसके अंदर list हो तो list mutable रहती है।
t = (1, [2, 3], 4)
print("Before:", t)
t[1].append(99)
print("After:", t)
Output:
Before: (1, [2, 3], 4)
After: (1, [2, 3, 99], 4)
Set mutable होता है — elements add/remove किए जा सकते हैं।
colors = {"red", "green"}
print("Before:", colors)
colors.add("blue")
print("After:", colors)
Output:
Before: {'red', 'green'}
After: {'red', 'blue', 'green'}
Integers immutable होते हैं — एक नई value assign करने से नया object बनता है।
x = 10
print("Before ID:", id(x))
x += 5
print("After ID:", id(x))
Output:
Different IDs → Integers are immutable
जब दो variables एक ही list को refer करते हैं तो एक को बदलने से दूसरा भी बदल जाता है।
A = [1, 2, 3]
B = A # Both refer to same object
B.append(4)
print("A:", A)
print("B:", B)
print("Same ID?", id(A) == id(B))
Output:
A: [1, 2, 3, 4]
B: [1, 2, 3, 4]
Same ID? True → Mutability confirmed