Sitemap

Python Interview Question [last part]

6 min readMar 25, 2025

--

For part 3, check this link.

1. What is PIP?

  • PIP is an acronym for Python Installer Package, which provides a seamless interface to install various Python modules.
  • It is a command-line tool that can search for a package over the internet and install it without any user intervention.

2. What is the ZIP function?

  • The zip() in Python is an in-built function that takes any number of iterables(list, str, etc) as an argument and aggregates them together by taking elements from each iterable passed as an argument.
  • It stops when the shortest iterable has been exhausted, and the elements in the longest iterables are left out.
  • Syntax: zip(*iterables)
  • Return Type: <class ‘zip’>
countries = ['India', 'US', 'UK', 'Canada']
capitals = ['Delhi', 'Washington DC', 'London', 'Ottawa']
country_capital = zip(countries, capitals)
print(country_capital)
print(list(country_capital))

# Output:
"""
<zip object at 0x7fce6586fb40>
[('India', 'Delhi'), ('US', 'Washington DC'), ('UK', 'London'), ('Canada', 'Ottawa')]
"""

3. What are iterable and iterator?

  • An iterable is an object of a series of elements that can be iterated.
  • For example, a list is an iterable: li = [1, 2, 3, 4, 5, 6]
  • An iterator is an object that is used to iterate over an iterable.
  • We can generate an iterator object using the iter method on an iterable.
  • Use the next function to get a value from an iterable using an iterator.
li = [1, 2, 3, 4, 5, 6]
iterator = iter(li)

print(next(iterator))
print(next(iterator))
print(next(iterator))
print(next(iterator))
print(next(iterator))
print(next(iterator))
print(next(iterator))

# Output
'''
1
2
3
4
5
6
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
next(iterator)
StopIteration
'''

Note: Once all the values underneath the iterable are read, an iterator object exhausts and raises the StopIteration error.

4. What are pickling and unpickling in Python?

The Pickle module in Python does the following things:

  • Accepts any Python object.
  • Converts it into a string representation.
  • Dumps it into a file using the dump function.

The Unpickle module in Python does the following things:

  • Fetches stored string representation.
  • Converts it back into its original Python object.

Pickle implementation:

import pickle

# Define a python object
person = {
"name": "Alice",
"age": 30,
"gender": "female"
}

# Pickle the object to a binary file
with open("person.pickle", "wb") as file:
pickle.dump(person, file)

print("Pickling completed")

Unpickle implementation:

import pickle

# load the data from the file
with open("person.pickle", "rb") as file:
data = pickle.load(file)

# print the data
print(data)

5. File Modes in Python:

File modes for normal operations:

Press enter or click to view image in full size

File modes for binary operations:

Press enter or click to view image in full size

6. Difference between Generators and Iterators in Python:

Press enter or click to view image in full size

🚀 Generators = Iterators but with less effort & more efficiency! 🎯

7. What is __init__() in Python?

  • The __init__() is equivalent to constructors in OOPs terminology.
  • It is reserved in Python classes and is called automatically whenever a new object is instantiated.
  • This method is used to initialize the object’s attribute with values.
  • While __init__() initializes the object, it does not allocate memory.
  • Memory allocation for a new object is handled by the __new__() method, which is called before __init__().

Get Bigie Billie’s stories in your inbox

Join Medium for free to get updates from this writer.

8. Access specifiers in Python

  • Python uses ‘_’ to determine the access control for a specific data member or a member function of a class.
  • A class in Python has 3 different types of Python access modifiers:

— Public Access Modifier:

  • Class members declared public are easily accessible from any part of the program.
  • All data members and member functions of a class are public by default.

— Protected Access Modifier:

  • The members of a class declared protected are only accessible to a class derived from it.
  • All data members of a class are declared protected by adding a single underscore ‘_’ symbol before the data members of that class.

— Private Access Modifier:

  • The members of a class that are declared private are accessible within the class only
  • The private access modifier is the most secure.
  • Data members of a class are declared private by adding a double underscore ‘__’ symbol before the data member of that class.

9. Unit tests in Python

10. Commonly used asserts in python?

self.assertEqual(10,add(5, 5)) # Passes if add(5, 5) equals 10
self.assertTrue(result) # Passes if result is True
self.assertFalse(error) # Passes if error is False
self.assertIs(result, expected_result) # Passes if result is expected_result (same object)
self.assertIsNone(result) # Passes if result is None
self.assertIsNotNone(result) # Passes if result is not None
self.assertIn(item, my_list) # Passes if item is present in my_list
self.assertRaises(ValueError, divide, 10, 0) # Passes if calling divide(10, 0) raises ValueError
self.assertAlmostEqual(result, expected_result, places=2) # Passes if result and expected_result are approximately equal up to 2 decimal places

11. Difference between unit test and pytest

Press enter or click to view image in full size

12. Exception groups in Python

  • The ExceptionGroup can be handled using a new except * syntax.
  • The * symbol indicates that multiple exceptions can be handled by each except* clause.
  • ExceptionGroup is a collection/group of different kinds of exceptions.
  • Without creating Multiple Exceptions, we can group different Exceptions, which we can later fetch one by one whenever necessary.
  • The order in which the Exceptions are stored in the Exception Group doesn’t matter while calling them.
try:
raise ExceptionGroup('Example Exception Group', (
TypeError('Example TypeError'),
ValueError('Example ValueError'),
KeyError('Example KeyError')
AttributeError('Example AttributeError')
)
except* TypeError:
...
except* (KeyError, ValueError, AttributeError) as e:
...
def process_values(values):
errors = []
for value in values:
try:
if not isinstance(value, int):
raise TypeError(f"Invalid Type: {value}(Expected int")
if value < 0:
raise ValueError(f"Negative value: {value}")
print(f"Processed: {value}")
except Exception as error:
errors.append(error)

# Input list with different errors
values = [10, -5, "Hello", 25, -1, "World"]

try:
process_values(values)
except* TypeError as type_errors: # Handles type errors properly
print("Caught TypeErrors: ", type_errors)
except* ValueError as value_errors: # Handles value errors separately
print("Caught ValueErrors:", value_errors)

# Output
'''
Processed: 10
Caught ValueErrors: ExceptionGroup('Processing errors', [ValueError('Negative value: -5'), ValueError('Negative value: -1')])
Caught TypeErrors: ExceptionGroup('Processing errors', [TypeError('Invalid type: hello (Expected int)'), TypeError('Invalid type: world (Expected int)')])
'''

13. Explain the Walrus Operator

  • The Walrus operator allows you to assign a value to a variable within an expression.
  • This can be useful when you need to use a value multiple times in a loop but don’t want to repeat the calculation.
  • The Walrus Operator is represented by the `:=` syntax.
  • It can be used in a variety of contexts, including while loops and if statements.

Note: Python versions before 3.8 don’t support the Walrus Operator.

names = ["Jacob", "Joe", "Jim"]

if (name := input("Enter a name: ")) in names:
print(f"Hello, {name}!")
else:
print("Name not found.")

14. What is partition() in Python?

  • The partition() method searches for a specified string and splits the string into a tuple containing three elements.
  • The first element contains the part before the specified string.
  • The second element contains the specified string.
  • The third element contains the part after the string.
text = "I could eat banana all day"
division = text.partition("bananas")
print(division)

# Output:
'''
('I could eat ', 'bananas', ' all day')
'''

print('abef'.partition('cd'))

# Output:
# ('abef','','')

I know this is quite detailed, but once you master everything in these four parts, failing a core Python interview will be almost impossible!!

All the best!

--

--

Bigie Billie
Bigie Billie

Written by Bigie Billie

as the name suggests, I am afraid of this big world, but altogether, I am chasing my dreams and finding answers to the big questions!!