CBSE Class 12 Computer Science
Question 102 of 136
Data File Handling — Question 41
Back to all questions 41
Question Give the output of the following snippet:
import pickle
list1, list2 = [2, 3, 4, 5, 6, 7, 8, 9, 10], []
for i in list1:
if (i % 2 == 0 and i % 4 == 0):
list2.append(i)
f = open("bin.dat", "wb")
pickle.dump(list2, f)
f.close()
f = open("bin.dat", "rb")
data = pickle.load(f)
f.close()
for i in data:
print(i)4
8
The code imports pickle module in Python. Initially, it creates two lists: list1 with numbers from 2 to 10 and list2 as an empty list. It then iterates through list1 and appends numbers divisible by both 2 and 4 to list2. After that, it opens a binary file named "bin.dat" in write-binary mode ("wb") and uses pickle.dump() to serialize list2 and write it to the file. The file is then closed. Later, the code opens the same file in read-binary mode ("rb") and uses pickle.load() to deserialize the data from the file into the variable data. Finally, it iterates through data and prints each element, which in this case are the numbers from list2 that satisfy the conditions (divisible by both 2 and 4).