Module-2
1. Explain the use of in and not in operators in list, strings and tuples with
examples.
The in and not in operators in Python are used to check for membership
that is, whether a value exists within a list, string, or tuple. These operators
return a boolean value: True if the item is found (in), or not found (not in),
and False otherwise.
Use in Lists
Lists are ordered collections of items. You can use in or not in to
check if an element is present in a list.
Examples
fruits = ["apple", "banana", "cherry"]
print("banana" in fruits) # True
print("orange" not in fruits) # True
Use in Strings
Strings are sequences of characters. You can check if a substring
exists in a string.
Example:
text = "Hello, world!"
print("world" in text) # True
print("Python" not in text) # True
Use in Tuples
Tuples are similar to lists but immutable. You can still use in and
not in to check for the presence of elements.
numbers = (1, 2, 3, 4, 5)
print(3 in numbers) # True
print(10 not in numbers) # True
Collection in Example not in Example
List "apple" in fruits "kiwi" not in fruits
String "cat" in "concatenate" "dog" not in "animals"
Tuple 2 in (1, 2, 3) 4 not in (1, 2, 3)
2. Explain negative indexing, slicing, index(), append(),remove(),del, (),insert()
reverse() and sort() with suitable examples for each.
1. Negative Indexing
Negative indexing allows you to access list elements from the end.
fruits = ['apple', 'banana', 'cherry']
print(fruits[-1]) # Output: cherry
print(fruits[-2]) # Output: banana
2. Slicing
Slicing retrieves a subset of a list using the syntax list[start:stop:step].
numbers = [10, 20, 30, 40, 50]
print(numbers[1:4]) # Output: [20, 30, 40]
print(numbers[:3]) # Output: [10, 20, 30]
print(numbers[::2]) # Output: [10, 30, 50]
3. index()
Returns the first index of a value in the list.
colors = ['red', 'blue', 'green', 'blue']
print(colors.index('blue')) # Output: 1
4. append()
Adds an element to the end of the list.
names = ['Alice', 'Bob']
names.append('Charlie')
print(names) # Output: ['Alice', 'Bob', 'Charlie']
5. remove()
Removes the first occurrence of a value from the list.
nums = [1, 2, 3, 2, 4]
nums.remove(2)
print(nums) # Output: [1, 3, 2, 4]
6. del
Deletes an item (or slice) by index or clears the entire list.
items = ['pen', 'pencil', 'eraser']
del items[1]
print(items) # Output: ['pen', 'eraser']
# Delete entire list
# del items
7. insert()
Inserts an item at a specific index.
letters = ['a', 'c', 'd']
letters.insert(1, 'b')
print(letters) # Output: ['a', 'b', 'c', 'd']
8. reverse()
Reverses the list in place.
nums = [1, 2, 3]
nums.reverse()
print(nums) # Output: [3, 2, 1]
9. sort()
Sorts the list in place in ascending order (by default).
scores = [40, 10, 30, 20]
scores.sort()
print(scores) # Output: [10, 20, 30, 40]
# Descending sort
scores.sort(reverse=True)
print(scores) # Output: [40, 30, 20, 10]
3. Explain about mutable and immutable data types in python with suitable
examples.
Mutable Data Types (Can be changed)
You can change the value after creating it.
Example: List
my_list = [1, 2, 3]
my_list.append(4)
print(my_list) # Output: [1, 2, 3, 4]
The list changed — it is mutable.
Immutable Data Types (Cannot be changed)
You cannot change the value after creating it.
Example: String
my_str = "hello"
my_str = my_str + " world"
print(my_str) # Output: "hello world"
A new string is created — the original didn't change. Strings are
immutable.
4. With neat example explain
a. How to get individual value from list
b. Getting a list from another list with slicing
c. How to find the length of a list
d. Changing the values in the list by using indexes
e. Finding a item in a list
a. How to get individual value from list
Use indexing (starts from 0):
my_list = [10, 20, 30, 40]
print(my_list[1]) # Output: 20
b. Getting a list from another list with slicing
Use slicing with start:stop format:
my_list = [10, 20, 30, 40, 50]
new_list = my_list[1:4] # Gets items from index 1 to 3
print(new_list) # Output: [20, 30, 40]
c. How to find the length of a list
Use the len() function:
my_list = [5, 10, 15, 20]
print(len(my_list)) # Output: 4
d. Changing the values in the list by using indexes
Just assign a new value using the index:
my_list = [1, 2, 3]
my_list[1] = 20
print(my_list) # Output: [1, 20, 3]
e. Finding an item in a list
Use the in keyword:
my_list = [10, 20, 30]
if 20 in my_list:
print("Found!") # Output: Found!
5. Explain about concatenation, replication and reverse() methods in list.
1. Concatenation
Joining two or more lists together using the + operator.
python
CopyEdit
list1 = [1, 2]
list2 = [3, 4]
result = list1 + list2
print(result) # Output: [1, 2, 3, 4]
2. Replication
Repeating the list multiple times using the * operator.
python
CopyEdit
my_list = [5, 6]
result = my_list * 3
print(result) # Output: [5, 6, 5, 6, 5, 6]
3. reverse() method
Reverses the order of the list in place (modifies the original list).
python
CopyEdit
my_list = [1, 2, 3, 4]
my_list.reverse()
print(my_list) # Output: [4, 3, 2, 1]
Summary Table:
Operation Description Example Result
Concatenation Join lists using + [1, 2] + [3] → [1, 2, 3]
Replication Repeat list using * [1, 2] * 2 → [1, 2, 1, 2]
reverse() Reverses list (modifies in place) [1, 2, 3].reverse() → [3, 2, 1]
6. Describe Enumerate() , random.choice() and random.shuffle() functions
in the list with examples.
1. enumerate()
Adds a counter/index to each item in a list.
Useful in loops when you need both the index and the item.
Example:
my_list = ['apple', 'banana', 'cherry']
for index, item in enumerate(my_list):
print(index, item)
Output:
0 apple
1 banana
2 cherry
2. random.choice()
Returns one random item from the list.
You need to import random first.
Example:
import random
my_list = [10, 20, 30, 40]
item = random.choice(my_list)
print(item) # Randomly prints one value like 20
3. random.shuffle()
Shuffles the list in place, changing the order randomly.
Also requires import random.
Example:
import random
my_list = [1, 2, 3, 4, 5]
random.shuffle(my_list)
print(my_list) # Output might be: [4, 1, 5, 2, 3]
7. Differentiate between list, tuples and dictionaries in python
Parameters List Tuple Set Dictionary
A list is an A tuple is an A set is an
A dictionary is an
ordered, mutable ordered, immutable unordered
Definition unordered collection
collection of collection of collection of
of key-value pairs.
elements. elements. unique elements.
Syntax includes Syntax includes Syntax includes Syntax includes
square brackets curved brackets curly brackets { , curly brackets { , }
Syntax
[ , ] with ‘,’ ( , ) with ‘,’ } with ‘,’ with ‘,’ separated
separated data. separated data. separated data. key-value data.
A list can be
A set dictionary
created using the Tuple can be A dictionary can be
can be created
Creation list() function or created using the created using the
using the set()
simple tuple() function. dict() function.
function.
assignment to [].
Empty An empty list An empty tuple An empty set can
An empty dictionary
Data can be created can be created by t be created by s =
can be created by {}.
Structure by l = []. = (). set().
It is an Ordered collection
It is an ordered It is also an
unordered in Python version
Order collection of ordered collection
collection of 3.7, unordered in
data. of data.
data. Python Version=3.6.
Parameters List Tuple Set Dictionary
Keys are unique, but
Duplicate data Duplicate data
Duplicate All elements are two different keys
entry is allowed entry is allowed in
Data unique in a Set. CAN have the same
in a List. a Tuple.
value.
Has integer
Also has integer Does NOT have Has a Key based
based indexing
Indexing based indexing that an index based indexing i.e. keys
that starts from
starts from ‘0’. mechanism. identify the value.
‘0’.
New items can
Being immutable, The add() update() method
be added using
Addition new data cannot be method adds an updates specific
the append()
added to it. element to a set. key-value pair.
method.
Pop() method Being immutable, Elements can be pop(key) removes
Deletion allows deleting no data can be randomly deleted specified key along
an element. popped/deleted. using pop(). with its value.
sort() method Immutable, so Unordered, so Keys are sorted by
Sorting sorts the sorting method is sorting is not using the sorted()
elements. not applicable. advised. method.
index() returns index() returns Unordered, so get(key) returns
Search index of first index of first searching is not value against
occurrence. occurrence. applicable. specified key.
Immutable, so Unordered, so No integer-based
reverse() method
Reversing reverse method is reverse is not indexing, so no
reverses the list.
not applicable. advised. reversal.
count() method
count() method
returns count() not count() not defined
Count returns occurrence
occurrence defined for sets. for dictionaries.
count.
count.
8. How is tuple different from a list and which function is used to convert
list to tuple.
The main difference between a list and a tuple in Python is that lists
are mutable (can be changed after creation) while tuples are immutable
(cannot be changed after creation). The built-in function tuple() can be used
to convert a list to a tuple.
Differences between Lists and Tuples:
Mutability:
Lists are mutable, meaning their elements can be added,
removed, or modified after the list is created. Tuples are
immutable, meaning their elements cannot be changed
after the tuple is created.
Syntax:
Lists are defined using square brackets [], while tuples are
defined using parentheses ().
Memory Usage and Performance:
Tuples are generally faster and more memory-efficient than
lists because they are immutable.
Methods:
Lists have more built-in methods for modification
(e.g., append(), insert(), remove()), while tuples have fewer
methods due to their immutability.
Converting a List to a Tuple:
The tuple() function can be used to convert a list to a tuple:
Python
my_list=[1,2,3,4,5]
my_tuple=tuple(my_list)
print(my_tuple) # Output: (1, 2, 3, 4, 5)
9. Create a function to print out a blank tic-tac-toe board
def print_blank_tic_tac_toe():
print(" | | ")
print("---|---|---")
print(" | | ")
print("---|---|---")
print(" | | ")
# Call the function
print_blank_tic_tac_toe()
Output:
| |
---|---|---
| |
---|---|---
| |
10. Explain id() , copy() and deepcopy() method with examples.
1. id() Function
Returns the unique memory address (identity) of an object.
Useful to check if two variables point to the same object.
Example:
a = [1, 2, 3]
b=a
print(id(a)) # e.g., 140005547260800
print(id(b)) # Same as 'a' → same object
2. copy() Method (Shallow Copy)
Creates a new object, but copies only the top level.
Nested objects are still shared between the original and the
copy.
Example:
import copy
original = [[1, 2], [3, 4]]
shallow = copy.copy(original)
original[0][0] = 99
print(shallow) # Output: [[99, 2], [3, 4]] → inner list changed
🔸 The outer list is copied, but the inner lists are shared.
3. deepcopy() Method (Deep Copy)
Copies everything, including nested objects.
The new object is completely independent.
Example:
import copy
original = [[1, 2], [3, 4]]
deep = copy.deepcopy(original)
original[0][0] = 99
print(deep) # Output: [[1, 2], [3, 4]] → no change in deep copy
🔹 deepcopy() makes a fully independent clone of the entire
structure.
11. Evaluate the below a. spam[int(int('3' * 2) // 11)] , if spam contains
the list[‘a’,’b’,’c’,’d’] b. list('hello')
a. spam[int(int('3' * 2) // 11)], where
spam = ['a', 'b', 'c', 'd']
Step-by-step breakdown:
1. '3' * 2 → '33' (string repetition)
2. int('33') → 33 (convert to integer)
3. 33 // 11 → 3 (integer division)
4. int(3) → 3
5. spam[3] → 'd' (index 3 of list ['a', 'b', 'c', 'd'])
Final result:
'd'
b. list('hello')
This converts the string 'hello' into a list of characters.
Result:
['h', 'e', 'l', 'l', 'o']
12. Discuss get(), item(), keys(), and values() methods in dictionary with
examples.
Let’s assume this dictionary:
student = {
"name": "Alice",
"age": 20,
"grade": "A"
}
1. get() Method
Used to safely access the value for a given key.
Returns None if the key is not found (or a default value if
specified).
Example:
print(student.get("name")) # Output: Alice
print(student.get("marks")) # Output: None
print(student.get("marks", 0)) # Output: 0 (default)
2. items() Method
Returns all key-value pairs as a list of tuples.
Example:
print(student.items())
# Output: dict_items([('name', 'Alice'), ('age', 20), ('grade', 'A')])
for key, value in student.items():
print(key, ":", value)
3. keys() Method
Returns a view of all keys in the dictionary.
Example:
print(student.keys())
# Output: dict_keys(['name', 'age', 'grade'])
for key in student.keys():
print(key)
4. values() Method
Returns a view of all values in the dictionary.
Example:
print(student.values())
# Output: dict_values(['Alice', 20, 'A'])
for value in student.values():
print(value)
13.What is the difference between copy.copy() and copy.deepcopy()?
1. copy.copy() – Shallow Copy
Creates a new object, but does not copy nested objects.
Outer object is copied, but inner objects are shared.
Example:
import copy
original = [[1, 2], [3, 4]]
shallow = copy.copy(original)
original[0][0] = 99
print(shallow) # Output: [[99, 2], [3, 4]]
The inner list was changed in both original and shallow, because
they share the same nested objects.
2. copy.deepcopy() – Deep Copy
Creates a completely independent copy, including all
nested objects.
Changes in one object do not affect the other.
Example:
import copy
original = [[1, 2], [3, 4]]
deep = copy.deepcopy(original)
original[0][0] = 99
print(deep) # Output: [[1, 2], [3, 4]]
The inner list in deep stays unchanged.
14. List the merits of dictionary over list.
1. Fast Lookup Using Keys
Dictionaries use keys for lookup, which is much faster than
searching through a list by index or value.
Ideal for when you need to retrieve data quickly.
# Dictionary lookup (fast)
data = {'name': 'Alice'}
print(data['name']) # O(1) time
2. Key-Value Pair Structure
Dictionaries store data as key-value pairs, making the
data more meaningful and organized.
# More meaningful than a list
student = {'name': 'Alice', 'age': 20, 'grade': 'A'}
3. No Need to Remember Indexes
You don’t need to remember the position of data as in lists
— just use the key.
# Easier to read than student[0] or student[1]
print(student['age'])
4. Dynamic and Flexible
You can add, remove, or update key-value pairs easily.
student['age'] = 21
student['course'] = 'Math'
5. Avoids Duplicates in Keys
Dictionaries do not allow duplicate keys, which helps in
maintaining unique identifiers.
6. Built-in Methods for Easy Access
Methods like keys(), values(), items(), and get() make data
access and manipulation easier.
15. Develop a program to accept a sentence from user and display the
longest word of that sentence along with its length.
# Accept sentence from user
sentence = input("Enter a sentence: ")
# Split the sentence into words
words = sentence.split()
# Initialize variables to track the longest word
longest_word = ""
max_length = 0
# Loop through each word to find the longest
for word in words:
if len(word) > max_length:
longest_word = word
max_length = len(word)
# Display the result
print("Longest word:", longest_word)
print("Length:", max_length)
Sample Output:
Enter a sentence: Python programming is enjoyable
Longest word: programming
Length: 11
16. Write a python program to count the number of occurrences of a
given word in a file.
# Ask user for filename and word to search
filename = input("Enter the filename: ")
search_word = input("Enter the word to search: ")
try:
# Open the file in read mode
file = open(filename, 'r')
# Read the file content
content = file.read()
# Convert content and search word to lowercase (for case-
insensitive search)
content = content.lower()
search_word = search_word.lower()
# Split content into words
words = content.split()
# Count occurrences
count = words.count(search_word)
# Print result
print(f"The word '{search_word}' occurs {count} time(s) in
the file.")
# Close the file
file.close()
except FileNotFoundError:
print("File not found. Please check the filename and try
again.")
17.Write the Python program that accepts a below given sentence and
build dictionary with
LETTERS,DIGITS,UPPERCASE,LOWERCASE as keys, and there
count in the sentences as values. Ex: Sentence=
”BIT@234Institute”D={“LETTERS”:12,”DIGITS”:3,”UPPERCASE
”:3,”LOWERCASE”:8}
# Accept input sentence from user
sentence = input("Enter a sentence: ")
# Initialize counts
letters = 0
digits = 0
uppercase = 0
lowercase = 0
# Loop through each character in the sentence
for char in sentence:
if char.isalpha():
letters += 1
if char.isupper():
uppercase += 1
elif char.islower():
lowercase += 1
elif char.isdigit():
digits += 1
# Create dictionary
D={
"LETTERS": letters,
"DIGITS": digits,
"UPPERCASE": uppercase,
"LOWERCASE": lowercase
}
# Print the dictionary
print(D)
Example Input & Output:
Input:
Enter a sentence: BIT@234Institute
Output:
{'LETTERS': 12, 'DIGITS': 3, 'UPPERCASE': 3, 'LOWERCASE': 8}
18. Demonstrate a. How dictionary items can be represented as a list of tuples.
b. How tuples can be used as keys in dictionaries?
a. How dictionary items can be represented as a list of tuples
In Python, you can convert a dictionary's key-value pairs into a list of
tuples using the items() method. Each tuple will contain a key and its
corresponding value.
Example:
# Creating a dictionary
student = {
"name": "Alice",
"age": 20,
"grade": "A"
}
# Convert dictionary items into a list of tuples
items_as_tuples = list(student.items())
# Print the list of tuples
print(items_as_tuples)
Output:
[('name', 'Alice'), ('age', 20), ('grade', 'A')]
Each item in the dictionary is converted into a tuple with the key as
the first element and the value as the second element.
The entire dictionary is represented as a list of these key-value pairs in
tuple form.
b. How tuples can be used as keys in dictionaries
In Python, tuples can be used as dictionary keys because they are
immutable (i.e., they cannot be changed after creation). This makes them
suitable as keys, as dictionary keys must be hashable and unchangeable.
Example:
# Creating a dictionary with tuples as keys
coordinate_dict = {
(0, 0): "Origin",
(1, 2): "Point A",
(3, 4): "Point B"
}
# Accessing value using tuple as key
print(coordinate_dict[(1, 2)]) # Output: Point A
Output: Point A
In the above example, the tuples (0, 0), (1, 2), and (3, 4) are used as
keys in the dictionary, and each tuple is associated with a point name.
Since tuples are immutable, they can be used as dictionary keys,
unlike lists which are mutable.
19.Write a python program to accept USN and Marks obtained, find maximum,
minimum and students USN who have scored in the range 100-85,85-75,75-
60 and below 60 separately.
# Input number of students
n = int(input("Enter number of students: "))
# Lists to store USNs and marks
usns = []
marks = []
# Input USN and marks
for i in range(n):
usn = input("Enter USN: ")
mark = int(input("Enter Marks (0-100): "))
usns.append(usn)
marks.append(mark)
# Find maximum and minimum marks
max_marks = max(marks)
min_marks = min(marks)
max_index = marks.index(max_marks)
min_index = marks.index(min_marks)
print("\nMaximum Marks:", max_marks, "USN:", usns[max_index])
print("Minimum Marks:", min_marks, "USN:", usns[min_index])
# Create lists for each range
range_100_85 = []
range_85_75 = []
range_75_60 = []
below_60 = []
# Categorize students
for i in range(n):
if marks[i] >= 85:
range_100_85.append(usns[i])
elif marks[i] >= 75:
range_85_75.append(usns[i])
elif marks[i] >= 60:
range_75_60.append(usns[i])
else:
below_60.append(usns[i])
# Print categorized USNs
print("\nStudents scoring 100–85:", range_100_85)
print("Students scoring 85–75:", range_85_75)
print("Students scoring 75–60:", range_75_60)
print("Students scoring below 60:", below_60)
Example Input/Output:
Enter number of students: 3
Enter USN: 1RV21CS001
Enter Marks (0-100): 88
Enter USN: 1RV21CS002
Enter Marks (0-100): 74
Enter USN: 1RV21CS003
Enter Marks (0-100): 59
Maximum Marks: 88 USN: 1RV21CS001
Minimum Marks: 59 USN: 1RV21CS003
Students scoring 100–85: ['1RV21CS001']
Students scoring 85–75: []
Students scoring 75–60: ['1RV21CS002']
Students scoring below 60: ['1RV21CS003']
20. Explain the concept of list slicing and list traversing with example.
List Slicing
Definition:
Slicing is used to extract a portion (sublist) of a list
using the
Syntax: list[start:stop:step]
start → index to start from (inclusive)
stop → index to stop at (exclusive)
step → (optional) interval between elements
Example:
numbers = [10, 20, 30, 40, 50, 60, 70]
print(numbers[1:4]) # Output: [20, 30, 40]
print(numbers[:3]) # Output: [10, 20, 30]
print(numbers[::2]) # Output: [10, 30, 50, 70]
print(numbers[::-1]) # Output: [70, 60, 50, 40, 30, 20, 10] (reversed list)
2. List Traversing
Definition:
Traversing a list means accessing each element one by
one, usually using a loop.
Example using for loop:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
Output:
apple
banana
cherry
Example using while loop:
i=0
while i < len(fruits):
print(fruits[i])
i += 1