Fundamentals 24 min read

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.

Python Programming Learning Circle
Python Programming Learning Circle
Python Programming Learning Circle
53 Python Interview Questions and Answers

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:

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))

3. What is the difference between "is" and "=="?

"==" checks for value equality, while "is" checks for object identity.

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

4. What is a decorator?

A decorator wraps a function, adding extra behavior before or after the original function runs.

def logging(func):
    def log_function_called():
        print(f'{func} called.')
        func()
    return log_function_called

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.

[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

6. Define a class Car with attributes color and speed, then return speed.

class Car:
    def __init__(self, color, speed):
        self.color = color
        self.speed = speed

car = Car('red', '100mph')
car.speed  # '100mph'

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.

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

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.

def add_three(x):
    return x + 3
li = [1,2,3]
list(map(add_three, li))  # [4,5,6]

10. How does reduce work?

Repeatedly applies a binary function to the items of a sequence, reducing it to a single value.

from functools import reduce
def add(x, y):
    return x + y
li = [1,2,3,5]
reduce(add, li)  # 11

11. How does filter work?

Filters elements of an iterable by a predicate function, keeping those that return True.

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]

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?

li = ['a','b','c']
li.reverse()  # ['c','b','a']

14. How does string multiplication work?

'cat' * 3  # 'catcatcat'

15. How does list multiplication work?

[1,2,3] * 2  # [1,2,3,1,2,3]

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?

a = [1,2]
b = [3,4,5]
a + b  # [1,2,3,4,5]

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.

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])

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.

round(5.12345, 3)  # 5.123

25. How to slice a list?

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]

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?

any([False, False])  # False
any([True, False])   # True
all([True, True])     # True

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.

value = 5
value += 1  # 6
value -= 2  # 4

33. Convert integer to binary.

bin(5)  # '0b101'

34. Remove duplicates from a list.

a = [1,1,1,2,3]
a = list(set(a))  # [1,2,3]

35. Check if a value exists in a list.

'a' in ['a','b','c']  # True

36. Difference between append and extend.

a = [1,2,3]
a.append(6)      # [1,2,3,6]
b = [1,2,3]
b.extend([4,5])   # [1,2,3,4,5]

37. Absolute value of an integer.

abs(-2)  # 2

38. Combine two lists into a list of tuples.

a = ['a','b','c']
b = [1,2,3]
list(zip(a,b))  # [('a',1),('b',2),('c',3)]

39. Sort a dictionary alphabetically.

d = {'c':3,'d':4,'b':2,'a':1}
sorted(d.items())  # [('a',1),('b',2),('c',3),('d',4)]

40. Class inheritance example.

class Car:
    def drive(self):
        print('vroom')
class Audi(Car):
    pass
Audi().drive()

41. Remove all spaces from a string.

s = 'A string with white space'
''.join(s.split())  # 'Astringwithwhitespace'

42. Why use enumerate() when iterating?

for idx, val in enumerate(['a','b','c']):
    print(idx, val)

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.

a = [1,2,3,4,5]
a3 = [i+1 for i in a]  # [2,3,4,5,6]

45. Ternary operator example.

'greater' if x > 6 else 'less'

46. Check if a string contains only digits.

'123'.isnumeric()  # True

47. Check if a string contains only letters.

'abc'.isalpha()  # True

48. Check if a string is alphanumeric.

'abc123'.isalnum()  # True

49. Get a list of dictionary keys.

d = {'id':7,'name':'Shiba'}
list(d)  # ['id','name']

50. Uppercase and lowercase a string.

'hello'.upper()  # 'HELLO'
'WORLD'.lower()  # 'world'

51. Difference between remove, del, and pop.

li = ['a','b','c']
li.remove('b')   # ['a','c']
del li[0]        # ['b','c']
li.pop(2)        # returns element, list shrinks

52. Dictionary comprehension example.

import string
alphabet = list(string.ascii_lowercase)
d = {val: idx for idx, val in enumerate(alphabet)}

53. Exception handling in Python.

try:
    # risky code
except Exception:
    # handle error
finally:
    # always execute

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.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

programminginterviewquestionspreparation
Python Programming Learning Circle
Written by

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.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.