Sequence Data Types – Chapter 5 | O Level M3-R5 | Boosting Skills

Sequence Data Types – NIELIT O Level (M3-R5)

इस chapter में हम Python के Sequence Data Types के बारे में सीखेंगे — Lists, Tuples और Dictionaries। इसमें Slicing, Indexing, Concatenation, Mutability जैसे concepts और कई उदाहरण जैसे maximum, minimum, mean निकालना, linear search और dictionary frequency count शामिल हैं।

👉 Swipe to see more
1️⃣ What are Sequence Data Types?

💡 Introduction

Python में Sequence Data Types वे data structures हैं जिनमें कई items को एक ordered sequence में store किया जा सकता है। इनकी खासियत है कि हर element का एक index number होता है जिससे हम किसी भी value को access कर सकते हैं।

📘 Definition: A sequence is an ordered collection of items where each item is associated with an index. Example – String, List, Tuple etc.

🧩 Features of Sequence Data Types

  • ✅ Ordered collection (items arranged in specific order)
  • ✅ Index-based access (0, 1, 2...)
  • ✅ Supports slicing, iteration, and concatenation
  • ✅ May be mutable (list) or immutable (string, tuple)

📘 Common Sequence Data Types in Python

Data TypeMutableExampleDescription
StringNo ❌"Hello"Characters arranged in sequence
ListYes ✅[1, 2, 3]Ordered, changeable collection
TupleNo ❌(1, 2, 3)Ordered, unchangeable collection
RangeNo ❌range(5)Represents sequence of numbers

🔍 Accessing Elements

हर sequence में items को उनकी index position से access किया जा सकता है। Index हमेशा 0 से शुरू होती है।

Example 1:

name = "PYTHON"
print(name[0])   # First character
print(name[3])   # Fourth character
    
Output:
P
H
Example 2: Negative Indexing

numbers = [10, 20, 30, 40, 50]
print(numbers[-1])   # Last element
print(numbers[-3])   # Third from end
    
Output:
50
30

✂️ Slicing in Sequences

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

➕ Concatenation and Repetition


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]

🔁 Iteration in Sequences


fruits = ["apple", "banana", "cherry"]
for item in fruits:
    print(item)
    
Output:
apple
banana
cherry

🧮 Operations on Sequences

OperationMeaningExampleOutput
len()Length of sequencelen([1,2,3])3
max()Maximum valuemax([5,1,8])8
min()Minimum valuemin((2,9,4))2
sum()Sum of all valuessum([2,4,6])12
inMembership check2 in [1,2,3]True

📗 Practical Example

Q. Calculate average marks using a list:

marks = [78, 85, 90, 66, 88]
total = sum(marks)
avg = total / len(marks)
print("Average Marks =", avg)
    
Output:
Average Marks = 81.4

🧠 Key Points

  • Sequence is a collection of ordered elements.
  • Indexing allows direct access to individual items.
  • Lists are mutable, Tuples and Strings are immutable.
  • Supports slicing, concatenation, iteration, and membership tests.

🧩 Summary

  • Sequence data types = Ordered collections in Python.
  • Most common: String, List, Tuple, Range.
  • Powerful for loops, pattern problems, and data manipulation.
2️⃣ Lists in Python

📘 Introduction

Python में List एक Ordered, Mutable (changeable) collection होती है जिसमें हम कई elements एक साथ रख सकते हैं। Lists को square brackets [ ] में लिखा जाता है। यह Python में सबसे ज़्यादा इस्तेमाल होने वाला sequence data type है।

💡 Syntax:


list_name = [element1, element2, element3, ...]
  

🧩 Example:


fruits = ["apple", "banana", "cherry"]
print(fruits)
  

Output:
['apple', 'banana', 'cherry']

📚 Properties of Lists

  • ✅ Ordered — Elements maintain their insertion order.
  • ✅ Mutable — You can change elements anytime.
  • ✅ Heterogeneous — Different data types allowed.
  • ✅ Index-based access — Supports positive and negative indexes.
  • ✅ Allows duplicate values.

🧱 Creating Lists


empty_list = []
numbers = [1, 2, 3, 4]
mixed = [10, "Python", 3.14, True]
nested = [[1, 2, 3], [4, 5, 6]]
  

🎯 Accessing Elements


animals = ["cat", "dog", "elephant", "tiger"]
print(animals[0])    # first element
print(animals[-1])   # last element
  

Output:
cat
tiger

✂️ Slicing a List


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]

🔁 Traversing a List


names = ["Amit", "Ravi", "Kiran"]
for name in names:
    print("Hello", name)
  

Output:
Hello Amit
Hello Ravi
Hello Kiran

🧩 Modifying Lists


nums = [10, 20, 30]
nums[1] = 99
nums.append(40)
nums.insert(1, 15)
print(nums)
  

Output:
[10, 15, 99, 30, 40]

🧹 Removing Elements


nums = [10, 20, 30, 40, 50]
nums.remove(30)
nums.pop(2)
del nums[0]
print(nums)
  

Output:
[40, 50]

📋 Common List Methods

MethodDescriptionExample
append()Add element at endlist.append(5)
insert()Insert at specific positionlist.insert(1, "Hi")
remove()Remove specific elementlist.remove(2)
pop()Remove last element or by indexlist.pop(2)
sort()Sort list ascendinglist.sort()
reverse()Reverse list orderlist.reverse()
copy()Return shallow copylist.copy()
clear()Remove all elementslist.clear()

➕ List Concatenation & Repetition


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]

🧮 Mathematical Functions


nums = [10, 20, 30, 40, 50]
print(len(nums))
print(max(nums))
print(min(nums))
print(sum(nums))
  

Output:
5
50
10
150

🔍 Membership Testing


colors = ["red", "green", "blue"]
print("red" in colors)
print("yellow" not in colors)
  

Output:
True
True

📘 Nested Lists


matrix = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9]
]
print(matrix[1][2])
  

Output:
6

💻 Practical Programs

Q1. Find largest number in list:

nums = [12, 45, 23, 67, 34]
largest = max(nums)
print("Largest =", largest)
    

Output:
Largest = 67

Q2. Count even and odd numbers:

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

Q3. Reverse list without reverse():

nums = [10, 20, 30, 40]
rev = nums[::-1]
print(rev)
    

Output:
[40, 30, 20, 10]

Q4. Find sum of all elements:

data = [5, 10, 15, 20]
total = 0
for i in data:
    total += i
print("Total =", total)
    

Output:
Total = 50

Q5. Remove duplicates:

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]

Q6. Generate square list using comprehension:

nums = [1, 2, 3, 4, 5]
squares = [n * n for n in nums]
print(squares)
    

Output:
[1, 4, 9, 16, 25]

Q7. Find 2nd largest element:

nums = [10, 40, 20, 50, 30]
nums.sort()
print("Second Largest =", nums[-2])
    

Output:
Second Largest = 40

Q8. Multiply all numbers:

nums = [2, 3, 4]
product = 1
for n in nums:
    product *= n
print("Product =", product)
    

Output:
Product = 24

Q9. Separate positive and negative numbers:

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]

Q10. Print even numbers only:

nums = [11, 12, 13, 14, 15, 16]
for i in nums:
    if i % 2 == 0:
        print(i)
    

Output:
12
14
16

🧠 Summary

  • Lists are ordered, mutable, and dynamic.
  • They allow multiple data types in one structure.
  • Support slicing, iteration, and nested structures.
  • Most versatile Python data structure.
3️⃣ Tuples in Python

📘 Introduction

Tuple Python का एक ordered and immutable (unchangeable) collection data type है। Tuple को parentheses ( ) में लिखा जाता है। यह list की तरह दिखता है लेकिन इसमें एक बार value assign करने के बाद उसे बदला नहीं जा सकता।

💡 Definition:

A tuple is an ordered collection of elements enclosed in parentheses ( ) and is immutable (cannot be changed after creation).

🔹 Syntax:


tuple_name = (element1, element2, element3, ...)
  

🔹 Example:


fruits = ("apple", "banana", "cherry")
print(fruits)
  

Output:
('apple', 'banana', 'cherry')

🧩 Creating Tuples


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
  

🎯 Accessing Elements (Indexing)


colors = ("red", "green", "blue", "yellow")
print(colors[0])
print(colors[-1])
  

Output:
red
yellow

✂️ Slicing Tuples


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)

📚 Tuple Characteristics

  • ✅ Ordered – Elements maintain their order
  • 🚫 Immutable – Cannot change, add, or remove items
  • ✅ Allow duplicate values
  • ✅ Can contain heterogeneous data
  • ✅ Faster than lists (performance-wise)

⚖️ Difference Between List and Tuple

FeatureListTuple
DefinitionOrdered, mutable collectionOrdered, immutable collection
Syntax[ ] square brackets( ) parentheses
MutabilityMutableImmutable
PerformanceSlowerFaster
Use CaseWhen data may changeWhen data should stay constant

➕ Tuple Operations


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)

🔍 Membership Testing


nums = (10, 20, 30, 40)
print(20 in nums)
print(50 not in nums)
  

Output:
True
True

🧮 Tuple Functions


nums = (10, 20, 30, 40, 50)
print(len(nums))
print(max(nums))
print(min(nums))
print(sum(nums))
  

Output:
5
50
10
150

📘 Tuple Methods

MethodDescriptionExample
count()Returns number of occurrences of a valuet.count(2)
index()Returns index of first occurrencet.index(10)

🧠 Iterating Through a Tuple


animals = ("dog", "cat", "horse")
for a in animals:
    print(a)
  

Output:
dog
cat
horse

🔁 Converting Between List and Tuple


t = (1, 2, 3)
l = list(t)  # tuple to list
l.append(4)
t2 = tuple(l)
print(t2)
  

Output:
(1, 2, 3, 4)

💻 Practical Programs

Q1. Find maximum and minimum in tuple:

nums = (45, 12, 89, 33, 67)
print("Max:", max(nums))
print("Min:", min(nums))
    

Output:
Max: 89
Min: 12

Q2. Count frequency of an element:

t = (1, 2, 3, 2, 2, 4, 5)
print("2 appears", t.count(2), "times")
    

Output:
2 appears 3 times

Q3. Find index of a specific element:

t = (10, 20, 30, 40)
print("Index of 30:", t.index(30))
    

Output:
Index of 30: 2

Q4. Iterate tuple with index:

cities = ("Delhi", "Mumbai", "Kolkata")
for i in range(len(cities)):
    print(i, ":", cities[i])
    

Output:
0 : Delhi
1 : Mumbai
2 : Kolkata

Q5. Check element existence:

colors = ("red", "blue", "green")
if "blue" in colors:
    print("Yes, blue is present!")
    

Output:
Yes, blue is present!

Q6. Tuple unpacking:

student = ("Amit", 20, "Delhi")
name, age, city = student
print("Name:", name)
print("Age:", age)
print("City:", city)
    

Output:
Name: Amit
Age: 20
City: Delhi

Q7. Nested Tuple Example:

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

Output:
3

Q8. Convert list of tuples into dictionary:

data = [("a", 1), ("b", 2), ("c", 3)]
d = dict(data)
print(d)
    

Output:
{'a': 1, 'b': 2, 'c': 3}

Q9. Find repeated elements in tuple:

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]

💡 Interview Style Questions

  • Q: Why are tuples faster than lists?
    A: Tuples are stored in fixed memory and are immutable, so Python optimizes their memory usage.
  • Q: Can we change a value inside tuple?
    A: No, tuple elements cannot be changed once created.
  • Q: How can we modify a tuple indirectly?
    A: Convert it into a list → make changes → convert back into tuple.

🧠 Summary

  • Tuples are ordered, immutable collections.
  • Faster than lists and use less memory.
  • Useful when data should remain constant.
  • Only two main methods: count() and index().
4️⃣ Dictionaries in Python

📘 Introduction

Python में Dictionary एक unordered, mutable, and key-value pair data type है। यह real-world mapping (जैसे student → marks) को store करने के लिए use होता है। Dictionary को curly braces { } में लिखा जाता है।

💡 Definition:

A dictionary is an unordered collection of key-value pairs where each key is unique. Dictionaries are mutable and written in curly braces { }.

🔹 Syntax:


dict_name = {
    key1: value1,
    key2: value2,
    key3: value3
}
  

🔹 Example:


student = {"name": "Amit", "age": 20, "course": "Python"}
print(student)
  

Output:
{'name': 'Amit', 'age': 20, 'course': 'Python'}

🧩 Characteristics of Dictionaries

  • ✅ Data stored as key : value pairs
  • ✅ Unordered (from Python 3.7+, maintains insertion order)
  • ✅ Mutable — can change, add, or remove pairs
  • 🚫 Keys must be unique and immutable
  • ✅ Values can be any data type

🧱 Creating Dictionaries


empty_dict = {}
student = {"name": "Ravi", "age": 18, "grade": "A"}
numbers = {1: "one", 2: "two", 3: "three"}
nested = {"person": {"name": "Amit", "age": 22}}
  

🎯 Accessing Elements


student = {"name": "Amit", "age": 20, "course": "Python"}
print(student["name"])
print(student.get("age"))
  

Output:
Amit
20

✍️ Adding and Updating Values


student = {"name": "Amit", "age": 20}
student["course"] = "Python"
student["age"] = 21
print(student)
  

Output:
{'name': 'Amit', 'age': 21, 'course': 'Python'}

❌ Removing Items


student = {"name": "Amit", "age": 20, "course": "Python"}
student.pop("age")       # removes key
del student["course"]    # delete key
student.clear()          # removes all
print(student)
  

Output:
{}

📋 Dictionary Methods

MethodDescriptionExample
keys()Returns list of keysd.keys()
values()Returns list of valuesd.values()
items()Returns key-value pairsd.items()
get()Returns value for a keyd.get('name')
pop()Removes specific keyd.pop('age')
update()Adds or updates key-value pairsd.update({'grade': 'A'})
clear()Removes all itemsd.clear()
copy()Copies dictionaryd.copy()

🔍 Iterating Through Dictionary


student = {"name": "Amit", "age": 20, "course": "Python"}
for key, value in student.items():
    print(key, ":", value)
  

Output:
name : Amit
age : 20
course : Python

🧮 Built-in Functions


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}

🔗 Combining Dictionaries


d1 = {"a": 1, "b": 2}
d2 = {"c": 3, "d": 4}
d1.update(d2)
print(d1)
  

Output:
{'a': 1, 'b': 2, 'c': 3, 'd': 4}

💻 Practical Programs

Q1. Count frequency of characters in a string:

text = "banana"
freq = {}
for ch in text:
    freq[ch] = freq.get(ch, 0) + 1
print(freq)
    

Output:
{'b': 1, 'a': 3, 'n': 2}

Q2. Merge two dictionaries:

d1 = {"x": 10, "y": 20}
d2 = {"z": 30}
merged = {**d1, **d2}
print(merged)
    

Output:
{'x': 10, 'y': 20, 'z': 30}

Q3. Find sum of dictionary values:

data = {"a": 100, "b": 200, "c": 300}
print("Sum =", sum(data.values()))
    

Output:
Sum = 600

Q4. Check if key exists:

data = {"id": 1, "name": "Amit"}
if "id" in data:
    print("Key found")
    

Output:
Key found

Q5. Find maximum value key:

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

Q6. Create dictionary from two lists:

keys = ["name", "age", "city"]
values = ["Ravi", 20, "Delhi"]
info = dict(zip(keys, values))
print(info)
    

Output:
{'name': 'Ravi', 'age': 20, 'city': 'Delhi'}

Q7. Nested dictionary example:

students = {
  "101": {"name": "Amit", "age": 20},
  "102": {"name": "Ravi", "age": 22}
}
print(students["102"]["name"])
    

Output:
Ravi

Q8. Remove duplicates from dictionary values:

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}

Q9. Swap keys and values:

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'}

Q10. Filter dictionary (keep only values > 10):

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}

💡 Interview Questions

  • Q: Are dictionaries ordered?
    A: Yes, from Python 3.7+, they maintain insertion order.
  • Q: Can a dictionary have duplicate keys?
    A: No, keys must be unique. If repeated, last value overrides previous one.
  • Q: Can we use list as a key?
    A: No, keys must be immutable (only string, number, or tuple allowed).
  • Q: How to merge two dictionaries?
    A: Using update() or unpacking operator {**d1, **d2}.

🧠 Summary

  • Dictionaries store key-value pairs and are mutable.
  • Keys must be unique and immutable.
  • Provide fast lookups and flexible structure.
  • Used for mapping, configurations, JSON data, etc.
5️⃣ Sets in Python

📘 Introduction

Python में Set एक unordered, mutable collection है जो unique elements को store करता है। यानी set में कोई भी duplicate value नहीं होती। Set का use mathematical set operations जैसे Union, Intersection, Difference के लिए किया जाता है।

💡 Definition:

A set is an unordered collection of unique and immutable elements enclosed in curly braces { }.

🔹 Syntax:


set_name = {element1, element2, element3, ...}
  

🔹 Example:


fruits = {"apple", "banana", "cherry"}
print(fruits)
  

Output:
{'banana', 'cherry', 'apple'}

🧩 Characteristics of Sets

  • ✅ Unordered – No fixed sequence
  • ✅ Mutable – Can add or remove items
  • 🚫 No duplicate values allowed
  • ✅ Elements must be immutable (numbers, strings, tuples)
  • 🚫 Does not support indexing or slicing

🧱 Creating Sets


empty_set = set()          # not {}
numbers = {1, 2, 3, 4}
mixed = {10, "Python", 3.14, True}
  

🎯 Adding and Removing Elements


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}

📋 Common Set Methods

MethodDescriptionExample
add()Adds an elements.add(5)
update()Adds multiple elementss.update([1,2])
remove()Removes element; error if not founds.remove(3)
discard()Removes element; no error if missings.discard(10)
pop()Removes random elements.pop()
clear()Removes all elementss.clear()
copy()Copies sets.copy()

➕ Set Operations


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}

🔍 Membership Test


colors = {"red", "green", "blue"}
print("red" in colors)
print("yellow" not in colors)
  

Output:
True
True

🧮 Built-in Functions


nums = {10, 20, 30, 40, 50}
print(len(nums))
print(max(nums))
print(min(nums))
print(sum(nums))
  

Output:
5
50
10
150

💻 Practical Programs

Q1. Remove duplicates from list using set:

nums = [1, 2, 2, 3, 4, 4, 5]
unique = set(nums)
print(unique)
    

Output:
{1, 2, 3, 4, 5}

Q2. Check common elements between two sets:

A = {1, 2, 3, 4}
B = {3, 5, 6, 2}
common = A & B
print("Common:", common)
    

Output:
Common: {2, 3}

Q3. Find difference between sets:

A = {1, 2, 3, 4}
B = {3, 4, 5}
print(A - B)
    

Output:
{1, 2}

Q4. Create set of vowels from string:

word = "programming"
vowels = {'a', 'e', 'i', 'o', 'u'}
result = set(word) & vowels
print(result)
    

Output:
{'a', 'i', 'o'}

Q5. Count unique words in sentence:

sentence = "python is easy and python is powerful"
words = set(sentence.split())
print("Unique words:", len(words))
    

Output:
Unique words: 5

Q6. Compare two sets completely:

A = {1, 2, 3}
B = {1, 2, 3}
print(A == B)
    

Output:
True

Q7. Subset and Superset check:

A = {1, 2}
B = {1, 2, 3, 4}
print(A.issubset(B))
print(B.issuperset(A))
    

Output:
True
True

Q8. Find elements unique to each set:

A = {1, 2, 3}
B = {3, 4, 5}
print(A ^ B)
    

Output:
{1, 2, 4, 5}

Q9. Remove all elements from a set:

A = {10, 20, 30}
A.clear()
print(A)
    

Output:
set()

Q10. Convert list to set and back:

nums = [1, 2, 2, 3, 3, 4]
unique_list = list(set(nums))
print(unique_list)
    

Output:
[1, 2, 3, 4]

💡 Interview Questions

  • Q: Why sets don’t allow duplicates?
    A: Because sets internally use hashing, and each hash must be unique.
  • Q: Can we store list in a set?
    A: No, because lists are mutable (unhashable).
  • Q: How do you add multiple elements at once?
    A: Using update() method.
  • Q: What is the difference between remove() and discard()?
    A: remove() gives error if element not found, discard() does not.

🧠 Summary

  • Set is an unordered, mutable collection of unique elements.
  • Used for mathematical operations like union/intersection.
  • No duplicate or indexing allowed.
  • Best for fast membership testing and unique data storage.
6️⃣ Slicing, Indexing, and Concatenation in Python

📘 Introduction

Python में Indexing, Slicing, और Concatenation sequence data types (जैसे list, string, tuple) के साथ काम करने के लिए basic और powerful concepts हैं। इनका use data को access, extract और combine करने के लिए किया जाता है।

🧱 1️⃣ Indexing

Indexing का मतलब होता है किसी sequence के element को उसकी position (index number) से access करना। Python में indexing 0 से शुरू होती है।

💡 Syntax:


sequence[index]
  

📘 Example (String):


name = "PYTHON"
print(name[0])   # First character
print(name[3])   # Fourth character
print(name[-1])  # Last character
  

Output:
P
H
N

📘 Example (List):


fruits = ["apple", "banana", "cherry", "mango"]
print(fruits[1])
print(fruits[-2])
  

Output:
banana
cherry

💡 Note: Negative indexing backward counting करता है: -1 last item, -2 second last, etc.

✂️ 2️⃣ Slicing

Slicing का मतलब है किसी sequence का हिस्सा (subsequence) निकालना। यह तीन parameters पर आधारित होता है:

  • start → जहाँ से slice शुरू होता है
  • stop → जहाँ slice रुकता है (excluded)
  • step → कितनी दूरी पर elements लिए जाएँ

💡 Syntax:


sequence[start : stop : step]
  

📘 Example (String Slicing):


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

📘 Example (List Slicing):


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]

Tip: Slicing हमेशा एक नया object return करता है, original sequence change नहीं होती।

🔗 3️⃣ Concatenation

Concatenation का मतलब है दो या अधिक sequences को जोड़ना (combine करना)। Python में + operator से concatenation किया जाता है।

📘 Example (String Concatenation):


a = "Hello"
b = "World"
result = a + " " + b
print(result)
  

Output:
Hello World

📘 Example (List Concatenation):


list1 = [1, 2, 3]
list2 = [4, 5, 6]
merged = list1 + list2
print(merged)
  

Output:
[1, 2, 3, 4, 5, 6]

📘 Example (Tuple Concatenation):


t1 = (10, 20)
t2 = (30, 40)
print(t1 + t2)
  

Output:
(10, 20, 30, 40)

⚠️ Note: Only same data type sequences can be concatenated — string + string, list + list, tuple + tuple.

🧮 Advanced Slicing Examples


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

📘 Slicing with Step Values


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]

💻 Practical Programs

Q1. Reverse a string using slicing:

text = "python"
rev = text[::-1]
print(rev)
    

Output:
nohtyp

Q2. Extract first and last three characters:

word = "programming"
print(word[:3] + word[-3:])
    

Output:
proing

Q3. Join two lists and find total length:

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

Q4. Remove middle elements using slicing:

nums = [10, 20, 30, 40, 50, 60]
print(nums[:2] + nums[-2:])
    

Output:
[10, 20, 50, 60]

Q5. Extract every alternate character:

txt = "PYTHONPROGRAM"
print(txt[::2])
    

Output:
PTOPORM

Q6. Merge two tuples of student names:

boys = ("Amit", "Ravi")
girls = ("Neha", "Pooja")
students = boys + girls
print(students)
    

Output:
('Amit', 'Ravi', 'Neha', 'Pooja')

Q7. Copy list using slicing:

A = [10, 20, 30]
B = A[:]
print(B)
    

Output:
[10, 20, 30]

Q8. Get substring from user input:

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

Q9. Reverse list using slicing:

nums = [1, 2, 3, 4, 5]
print(nums[::-1])
    

Output:
[5, 4, 3, 2, 1]

Q10. Check palindrome using slicing:

word = "madam"
if word == word[::-1]:
    print("Palindrome")
else:
    print("Not Palindrome")
    

Output:
Palindrome

💬 Interview Questions

  • Q: What does slicing return?
    A: A new subsequence (string, list, or tuple).
  • Q: Is slicing mutable?
    A: No, slicing itself creates a new object; original sequence remains unchanged.
  • Q: Can we slice a tuple?
    A: Yes, slicing works on tuples but the result is a new tuple.
  • Q: What is difference between indexing and slicing?
    A: Indexing fetches one element; slicing fetches a range of elements.
  • Q: What is concatenation operator?
    A: The + operator joins two sequences of same type.

🧠 Summary

  • Indexing → Access single element by position.
  • Slicing → Extract a range using start:stop:step.
  • Concatenation → Combine multiple sequences.
  • Works with strings, lists, and tuples.
  • Powerful tool for data manipulation and copying.
7️⃣ Concept of Mutability in Python

📘 Introduction

Python में हर object (जैसे list, tuple, string, set, dictionary आदि) memory में एक reference के रूप में store होता है। Mutability यह बताती है कि कोई object memory में बदल सकता है या नहीं।

  • Mutable objects – जिन्हें हम change (modify) कर सकते हैं।
  • 🚫 Immutable objects – जिन्हें एक बार बनाने के बाद बदला नहीं जा सकता।

💡 Simple Meaning:

- Mutable → Changeable in place (same memory id)
- Immutable → Creates new object when changed

🧱 Examples of Mutable & Immutable Types

CategoryData TypeMutable?
SequenceList✅ Mutable
SequenceTuple🚫 Immutable
SequenceString🚫 Immutable
MappingDictionary✅ Mutable
SetSet✅ Mutable
Numericint, float, complex🚫 Immutable

🔹 1️⃣ Mutable Objects Example


# 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)

🔹 2️⃣ Immutable Objects Example


# 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)

💡 How Mutability Works Internally

जब आप 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)

🧩 Example: Mutable List vs Immutable Tuple


# 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)

📘 Mutable Dictionary Example


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)

🔍 Check Mutability using id()


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

💻 Practical Programs

Q1. Demonstrate mutability with list:

L = [1, 2, 3]
print("Before:", L)
L[0] = 100
print("After:", L)
    

Output:
Before: [1, 2, 3]
After: [100, 2, 3]

Q2. Demonstrate immutability with string:

s = "hello"
try:
    s[0] = "H"
except TypeError as e:
    print(e)
    

Output:
'str' object does not support item assignment

Q3. Show memory id difference:

num = 5
print(id(num))
num += 1
print(id(num))
    

Output:
Different ids → immutable

Q4. Modify dictionary in place:

data = {"x": 10, "y": 20}
data["z"] = 30
print(data)
    

Output:
{'x': 10, 'y': 20, 'z': 30}

Q5. Tuple immutability test:

t = (1, 2, 3)
try:
    t[1] = 99
except TypeError:
    print("Tuple is immutable")
    

Output:
Tuple is immutable

💬 Interview Questions

  • Q: What is mutability in Python?
    A: The ability of an object to change its content without changing its identity (memory address).
  • Q: Is string mutable?
    A: No, string is immutable.
  • Q: Which data types are mutable?
    A: Lists, Dictionaries, Sets.
  • Q: Which data types are immutable?
    A: Strings, Tuples, Integers, Floats.
  • Q: How to test mutability?
    A: By comparing id() before and after modification.

🧠 Summary

  • Mutability defines if an object can be changed after creation.
  • Mutable: list, dict, set → changeable in place.
  • Immutable: str, tuple, int, float → new object created when modified.
  • Check memory ids using id() function.
🧮 8 Practical Examples on Mutability

💡 Example 1: Modifying a List (Mutable Object)

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

💡 Example 2: String Modification (Immutable)

Strings immutable होते हैं — किसी भी परिवर्तन से नया object बनता है।


text = "Python"
print("Before ID:", id(text))
text += "3.11"
print("After ID:", id(text))
  

Output:
Different IDs → Immutable

💡 Example 3: Modifying a Dictionary (Mutable)

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

💡 Example 4: Tuples are Immutable

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

💡 Example 5: Mutable Inside Immutable (Nested Example)

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)

💡 Example 6: Set Modification

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'}

💡 Example 7: Integer Immutability

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

💡 Example 8: Copying Mutable Objects

जब दो 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