TechSchool
Home / Interview questions / Python

Python interview questions

44 questions about Python with short answers and code. Each answer links to a full lesson on this site. Free, with no signup and no ads.

Basics

1. What is Python?

Python is a high-level scripting language. It is interpreted and object-oriented. The code is easy to read.

Full lesson: Python3 intro

2. How do you set up Python on your computer?

Download Python from the official site and run the installer. Check the install with the version command.

python3 --version

Full lesson: Python3 install

3. What is a basic rule for Python identifiers?

The first character must be a letter or an underscore. The other parts can be letters, digits, or underscores. Identifiers are case-sensitive.

count = 1
Count = 2

Full lesson: Python3 basic syntax

4. How do you write an if-else statement in Python?

Use the if keyword and a condition. Add a colon and an indented block. Use else for the other case.

x = 5
if x > 0:
    print("positive")
else:
    print("not positive")

Full lesson: Python if else

5. How do you loop over the items in a list?

Use a for loop. The loop visits each item in the list.

for item in [1, 2, 3]:
    print(item)

Full lesson: Python for loop2

6. How do you define a function in Python?

Use the def keyword and a function name. Add a colon and an indented body. Use return to send a value back.

def add(a, b):
    return a + b

print(add(2, 3))

Full lesson: Python3 function

7. How do you join list elements into one string?

Use the join() method. Call it on the delimiter string. Pass the list as the argument.

my_list = ['Hello', 'World', 'Python']
result = ' '.join(my_list)
print(result)

Full lesson: Python join list

8. How do you merge two lists into one?

Use the + operator. It makes a new list with the items of both lists.

list1 = [1, 2, 3]
list2 = [4, 5, 6]
merged_list = list1 + list2
print(merged_list)

Full lesson: Python merge lists

9. How do you find the position of a substring in a string?

Use the index() method. It returns the start position of the substring. It raises an exception if the substring is not there.

text = "runoob"
print(text.index("noo"))

Full lesson: Python3 string index

10. How do you find the last position of a substring in a string?

Use the rindex() method. It returns the position of the last match. It raises an exception if there is no match.

text = "runoob"
print(text.rindex("o"))

Full lesson: Python3 string rindex

11. How do you add the numbers in a list?

Use the sum() function. It adds all numbers in the list and returns the total.

numbers = [1, 2, 3, 4]
print(sum(numbers))

Full lesson: Python list sum

12. How do you make a subclass with inheritance?

Put the parent class name in parentheses after the subclass name. The subclass gets the attributes and methods of the parent. The subclass can override a method.

class Animal:
    def speak(self):
        return "sound"

class Dog(Animal):
    def speak(self):
        return "bark"

Full lesson: Python subclass inheritance

13. How do you import a module in Python?

Use the import statement. Then use the module name and a dot to call its items.

import math
print(math.sqrt(16))

Full lesson: Python3 module

14. How do you find the difference between two strings?

Use the Differ class from the difflib module. Call compare() on the two split strings. The result shows the changed lines.

import difflib
differ = difflib.Differ()
diff = differ.compare(["a"], ["b"])
print('\n'.join(diff))

Full lesson: Python string difference

Intermediate

15. Why does join() fail on a list of numbers?

The join() method needs strings. A list of numbers causes a TypeError. Convert each number to a string first.

nums = [1, 2, 3]
print(' '.join(str(n) for n in nums))

Full lesson: Python3 string join

16. What is a list in Python?

A list is a sequence of values. You write the values between square brackets and separate them with commas.

colors = ["red", "green", "blue"]

Full lesson: Python3 list

17. How do you access an item in a list by its index?

Use square brackets after the list name. The first index is 0.

colors = ["red", "green", "blue"]
print(colors[1])

Full lesson: Python3 list

18. How do you read a slice from a string?

Use square brackets with a start index and an end index. The slice includes the start index and stops before the end index.

text = "Hello World!"
print(text[0:5])

Full lesson: Python3 string

19. How do you copy a list in Python?

Use a slice with no indexes to make a shallow copy. The new list has the same items as the old list.

li1 = [4, 8, 2]
li2 = li1[:]
print(li2)

Full lesson: Python copy list

20. How do you check if a list is empty?

Use the not operator on the list. An empty list is false in a condition.

items = []
if not items:
    print("The list is empty")

Full lesson: Python empty list

21. How do you remove all items from a list?

Call the clear method on the list. The list stays but it has no items.

items = [1, 2, 3]
items.clear()
print(items)

Full lesson: Python clear list

22. How do you sort the items of a list?

Call the sort method on the list. The method changes the list in place.

nums = [3, 1, 2]
nums.sort()
print(nums)

Full lesson: Python sort list

23. How do you write text to a file and read it back?

Use the open function with a mode string. The with keyword closes the file for you.

with open("test.txt", "wt") as f:
    f.write("Hello")
with open("test.txt", "rt") as f:
    print(f.read())

Full lesson: Python3 file io

24. How do you use StringIO to work with text in memory?

Import StringIO from the io module. You can read and write the buffer like a file.

from io import StringIO
buf = StringIO()
buf.write("Hello")
print(buf.getvalue())

Full lesson: Python stringio

25. How do you find the union of two lists?

Convert each list to a set. Then use the union operator on the two sets.

a = [1, 2, 3]
b = [3, 4, 5]
print(set(a) | set(b))

Full lesson: Python list union

26. What happens when you use a list index that is out of range?

Python raises an IndexError. The index must be less than the length of the list.

items = [1, 2]
print(items[5])  # IndexError

Full lesson: Python3 list

27. Why does a copy made with = not create a new list?

The = operator binds a second name to the same list object. A change through one name appears through the other name.

a = [1, 2]
b = a
b.append(3)
print(a)  # [1, 2, 3]

Full lesson: Python copy list

28. Why does a for loop over a list fail when you remove items inside the loop?

The loop uses an internal index. When you remove an item, the later items move left and the loop skips some of them.

items = [1, 2, 3]
for x in items:
    items.remove(x)
print(items)  # [2]

Full lesson: Python3 loop

29. Why does a while loop run forever when you forget to update the condition variable?

The condition stays true, so the loop never stops. You must change the variable inside the loop body.

x = 0
while x < 3:
    print(x)
    x += 1

Full lesson: Python3 loop

Common mistakes

30. Why does a module import fail when the file name is wrong?

Python looks for a file with the module name and the .py suffix. A wrong name causes a ModuleNotFoundError.

import mymodule  # ModuleNotFoundError if mymodule.py is missing

Full lesson: Python3 module

31. How do you run a Python script from the command line?

Type python and the file name. The interpreter reads the file and runs the code.

python test.py

Full lesson: Python3 tutorial

32. How do you define a class in Python?

Use the class keyword and a class name. Put the class body under the class line.

class Dog:
    def bark(self):
        print("Woof")

Full lesson: Python3 class

33. How do you create an object from a class?

Call the class name like a function. The result is a new object of that class.

d = Dog()
d.bark()

Full lesson: Python3 class

34. How do you make a multiplication table with two loops?

Use one loop for the rows and one loop for the columns. Print each product on the same row.

for i in range(1, 10):
    for j in range(1, i + 1):
        print('{}x{}={}'.format(j, i, i * j), end=' ')
    print()

Full lesson: Python3 99 table

35. How do you sort a list without changing the original list?

Call the sorted() function on the list. The function returns a new sorted list and keeps the old list as it is.

numbers = [3, 1, 2]
new_list = sorted(numbers)
print(numbers)
print(new_list)

Full lesson: Python sort list

36. How do you install Python packages with uv?

Run the uv pip install command and give the package name. The tool adds the package to your environment.

uv pip install requests

Full lesson: Uv tutorial

37. How do you sort a list with the Shell sort method?

Shell sort compares items that are far apart. It then reduces the gap until the gap is zero.

def shellSort(arr):
    n = len(arr)
    gap = int(n / 2)
    while gap > 0:
        for i in range(gap, n):
            temp = arr[i]
        gap = int(gap / 2)

Full lesson: Python shellsort

38. How do you open a file with the with keyword?

Use the with keyword and the open() function. Python closes the file for you at the end of the block.

with open("test.txt", "rt") as in_file:
    text = in_file.read()
print(text)

Full lesson: Python3 file io

39. How do you check if a list is empty without len()?

Use the not operator on the list. An empty list gives False, so not gives True.

my_list = []
if not my_list:
    print("The list is empty")

Full lesson: Python empty list

40. Why does a list change when you edit its copy made with =?

The = sign does not copy a list. It gives a second name to the same list object.

a = [1, 2]
b = a
b.append(3)
print(a)

Full lesson: Python copy list

41. Why does sort() return None?

The sort() method changes the list in place. It returns None, so you must not assign its result to a variable.

numbers = [3, 1, 2]
numbers.sort()
print(numbers)

Full lesson: Python sort list

42. Why does a function fail when you forget the self parameter?

A method needs self as its first parameter. Without self, Python cannot find the object.

class Dog:
    def bark(self):
        print("Woof")

Full lesson: Python3 class

43. Why does a file read fail when you open it in write mode?

Mode "wt" removes the old file content. Use mode "rt" to read a file that already has text.

with open("test.txt", "rt") as in_file:
    print(in_file.read())

Full lesson: Python3 file io

44. Why does a set union remove duplicate items from two lists?

A set holds each item only one time. The union of two sets drops all repeated values.

list1 = [1, 2, 3]
list2 = [3, 4]
print(list(set(list1).union(set(list2))))

Full lesson: Python list union

More on TechSchool
See the Python cheat sheet JavaScript TypeScript HTML CSS React Vue 3 Node.js Java PHP C C++ C# Go SQL MongoDB Redis Linux Git Docker Data Structures