53 Python Interview Questions and Answers
This article compiles 53 common Python interview questions covering fundamentals such as data structures, functions, OOP, modules, and standard library features, each accompanied by concise explanations and code examples to help candidates and developers prepare effectively.
1. What is the difference between a list and a tuple?
Lists are mutable, ordered sequences that can be modified after creation, while tuples are immutable, ordered sequences that cannot be changed once created.
2. How do you perform string interpolation?
Three ways without importing Template:
<code>name = 'Chris'
# 1. f-strings
print(f'Hello {name}')
# 2. % operator
print('Hey %s %s' % (name, name))
# 3. format()
print("My name is {}".format(name))
</code>3. What is the difference between "is" and "=="?
"==" checks for value equality, while "is" checks for object identity.
<code>a = [1,2,3]
b = a
c = [1,2,3]
print(a == b) # True
print(a == c) # True
print(a is b) # True
print(a is c) # False
</code>4. What is a decorator?
A decorator wraps a function, adding extra behavior before or after the original function runs.
<code>def logging(func):
def log_function_called():
print(f'{func} called.')
func()
return log_function_called
</code>5. Explain the range function.
Generates a sequence of integers. It can take 1, 2, or 3 arguments: stop; start, stop; or start, stop, step.
<code>[i for i in range(10)] # 0-9
[i for i in range(2,10)] # 2-9
[i for i in range(2,10,2)] # 2,4,6,8
</code>6. Define a class Car with attributes color and speed, then return speed.
<code>class Car:
def __init__(self, color, speed):
self.color = color
self.speed = speed
car = Car('red', '100mph')
car.speed # '100mph'
</code>7. Difference between instance, static, and class methods.
Instance methods receive self , static methods use @staticmethod and have no access to class or instance data, and class methods receive cls and can modify class state.
<code>class CoffeeShop:
specialty = 'espresso'
def __init__(self, coffee_price):
self.coffee_price = coffee_price
def make_coffee(self):
print(f'Making {self.specialty} for ${self.coffee_price}')
@staticmethod
def check_weather():
print('Its sunny')
@classmethod
def change_specialty(cls, specialty):
cls.specialty = specialty
</code>8. Difference between func and func() .
func refers to the function object; func() calls the function and returns its result.
9. How does the map function work?
Applies a function to each element of an iterable, returning an iterator of results.
<code>def add_three(x):
return x + 3
li = [1,2,3]
list(map(add_three, li)) # [4,5,6]
</code>10. How does reduce work?
Repeatedly applies a binary function to the items of a sequence, reducing it to a single value.
<code>from functools import reduce
def add(x, y):
return x + y
li = [1,2,3,5]
reduce(add, li) # 11
</code>11. How does filter work?
Filters elements of an iterable by a predicate function, keeping those that return True.
<code>def is_even(x):
return x % 2 == 0
li = [1,2,3,4,5,6,7,8]
list(filter(is_even, li)) # [2,4,6,8]
</code>12. Are arguments passed by reference or by value?
Immutable objects (e.g., strings, numbers, tuples) behave as pass‑by‑value; mutable objects (e.g., lists) behave as pass‑by‑reference.
13. How to reverse a list?
<code>li = ['a','b','c']
li.reverse() # ['c','b','a']
</code>14. How does string multiplication work?
<code>'cat' * 3 # 'catcatcat'
</code>15. How does list multiplication work?
<code>[1,2,3] * 2 # [1,2,3,1,2,3]
</code>16. What does "self" refer to in a class?
It refers to the instance of the class on which a method is called.
17. How to concatenate two lists?
<code>a = [1,2]
b = [3,4,5]
a + b # [1,2,3,4,5]
</code>18. Shallow vs deep copy.
Shallow copy copies references; deep copy creates independent objects.
19. List vs NumPy array.
Lists are heterogeneous and part of Python's core; NumPy arrays are homogeneous, memory‑efficient, and support vectorized operations.
20. Concatenating two NumPy arrays.
<code>import numpy as np
a = np.array([1,2,3])
b = np.array([4,5,6])
np.concatenate((a,b)) # array([1,2,3,4,5,6])
</code>21. What do you like about Python?
Readability, a single “Pythonic” way to do things, and a rich ecosystem.
22. Favorite Python library?
Pandas, for data manipulation and analysis.
23. Mutable vs immutable objects.
Immutable: int, float, bool, str, tuple. Mutable: list, dict, set.
24. Round a number to three decimal places.
<code>round(5.12345, 3) # 5.123
</code>25. How to slice a list?
<code>a = [0,1,2,3,4,5,6,7,8,9]
a[:2] # [0,1]
a[8:] # [8,9]
a[2:8] # [2,3,4,5,6,7]
a[2:8:2] # [2,4,6]
</code>26. What is pickle?
Python's built‑in serialization module.
27. Difference between dict and JSON.
Dict is a Python object; JSON is a text format for data exchange.
28. Common Python ORMs.
SQLAlchemy (often with Flask) and Django ORM.
29. How do any() and all() work?
<code>any([False, False]) # False
any([True, False]) # True
all([True, True]) # True
</code>30. Lookup speed: dict vs list.
Dict lookup is O(1) average; list lookup is O(n).
31. Module vs package.
A module is a single file; a package is a directory of modules.
32. Incrementing and decrementing integers.
<code>value = 5
value += 1 # 6
value -= 2 # 4
</code>33. Convert integer to binary.
<code>bin(5) # '0b101'
</code>34. Remove duplicates from a list.
<code>a = [1,1,1,2,3]
a = list(set(a)) # [1,2,3]
</code>35. Check if a value exists in a list.
<code>'a' in ['a','b','c'] # True
</code>36. Difference between append and extend.
<code>a = [1,2,3]
a.append(6) # [1,2,3,6]
b = [1,2,3]
b.extend([4,5]) # [1,2,3,4,5]
</code>37. Absolute value of an integer.
<code>abs(-2) # 2
</code>38. Combine two lists into a list of tuples.
<code>a = ['a','b','c']
b = [1,2,3]
list(zip(a,b)) # [('a',1),('b',2),('c',3)]
</code>39. Sort a dictionary alphabetically.
<code>d = {'c':3,'d':4,'b':2,'a':1}
sorted(d.items()) # [('a',1),('b',2),('c',3),('d',4)]
</code>40. Class inheritance example.
<code>class Car:
def drive(self):
print('vroom')
class Audi(Car):
pass
Audi().drive()
</code>41. Remove all spaces from a string.
<code>s = 'A string with white space'
''.join(s.split()) # 'Astringwithwhitespace'
</code>42. Why use enumerate() when iterating?
<code>for idx, val in enumerate(['a','b','c']):
print(idx, val)
</code>43. Difference between pass, continue, and break.
pass does nothing; continue skips to the next loop iteration; break exits the loop.
44. Convert a for‑loop to a list comprehension.
<code>a = [1,2,3,4,5]
a3 = [i+1 for i in a] # [2,3,4,5,6]
</code>45. Ternary operator example.
<code>'greater' if x > 6 else 'less'
</code>46. Check if a string contains only digits.
<code>'123'.isnumeric() # True
</code>47. Check if a string contains only letters.
<code>'abc'.isalpha() # True
</code>48. Check if a string is alphanumeric.
<code>'abc123'.isalnum() # True
</code>49. Get a list of dictionary keys.
<code>d = {'id':7,'name':'Shiba'}
list(d) # ['id','name']
</code>50. Uppercase and lowercase a string.
<code>'hello'.upper() # 'HELLO'
'WORLD'.lower() # 'world'
</code>51. Difference between remove, del, and pop.
<code>li = ['a','b','c']
li.remove('b') # ['a','c']
del li[0] # ['b','c']
li.pop(2) # returns element, list shrinks
</code>52. Dictionary comprehension example.
<code>import string
alphabet = list(string.ascii_lowercase)
d = {val: idx for idx, val in enumerate(alphabet)}
</code>53. Exception handling in Python.
<code>try:
# risky code
except Exception:
# handle error
finally:
# always execute
</code>Conclusion
Interview questions can vary widely; the best preparation is extensive hands‑on coding experience. This list aims to cover the essential Python topics needed for data‑science or junior/mid‑level Python developer roles.
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.