Q-1 Tuple Vs list
Q-2 Explain Pickle & Unpickle.
The pickle module is used for implementing binary protocols for serializing
and de-serializing a Python object structure.
Pickling: It is a process where a Python object hierarchy is converted
into a byte stream.
Unpickling: It is the inverse of Pickling process where a byte stream is
converted into an object hierarchy.
import pickle
my_list = {15, 'Python', 'Hello World'}
# Pickling
with open("data.pickle","wb") as file_handle:
pickle.dump(my_list, file_handle, pickle.HIGHEST_PROTOCOL)
# Unpickling
with open("data.pickle","rb") as file_handle:
retrieved_data = pickle.load(file_handle)
print(retrieved_data)
Output
0.48s
set(['Python', 'Hello World', 15])
In line 1, we import the pickle module in Python.
In line 2, a demo Python list is created which will be pickled.
In lines 4 and 5, pickling is done. A .pickle file is created and the
Python object (here demo Python list) is dumped.
In lines 7 to 9, we have unpickled the pickled file which thereby gives
the demo Python list that was created as an output.
The dump()function is used to serialize an object hierarchy.
pickle.HIGHEST_PROTOCOL is an integer value that represents the highest
available protocol version.
The load() function is used to de-serialize a data stream.
Module Interface :
dumps() – This function is called to serialize an object hierarchy.
loads() – This function is called to de-serialize a data stream.
Constants provided by the pickle module :
1. pickle.HIGHEST_PROTOCOL
This is an integer value representing the highest protocol version
available. This is considered as the protocol value which is passed to
the functions dump(), dumps().
2. pickle.DEFAULT_PROTOCOL
This is an integer value representing the default protocol used for
pickling whose value may be less than the value of the highest
protocol.
Q-3