🎓 A1Learner
🔍

Home / Blog / Programming / Python

Top 50 Python Interview Questions with Answers

Programming · Python · 36 min read

Fifty Python interview questions with answers and code that was actually run: basics, data structures, functions, classes, generators, and more.

How to use this sheet

Fifty Python interview questions fill this sheet, arranged under topic headings. Answers stay brief. Most carry a short program, and each program here was run on Python 3.12.3, with the output shown exactly as the run produced it.

Use the sheet the way an interview works. Read the question, cover the answer, and say your own answer out loud. Then read the answer here and run the program yourself. An answer you can say without looking is an answer you own. An answer you only recognise is not.

The Python track on this site holds 270 lessons: 116 in Python Beginner, 52 in Python Intermediate, and 102 in Python Advanced. Each answer names the lesson that teaches the idea in full, so you can go deeper on any question that catches you out.

One gap is stated plainly here, not hidden. This sheet does not cover pandas or numpy. Both are taught in the Pandas course on this site, which has 50 lessons. Question 50 says what to do about them. Everything else in this sheet is covered by a lesson that already exists.

1. What is Python, and what is it used for?

Python is a programming language. It is a general-purpose language, which means it is not built for one job only. People use it for websites, for scripts that move files around, for data work, for testing, and for small tools.

Python reads like plain words more than most languages do. That is why beginners start with it, and why experienced programmers keep it for quick jobs. The Python Intro lesson in the Beginner course walks through the same idea with a first program.

Python is also the language of this site's own track. The three Python courses take you from a first print statement to decorators, generators, and asyncio. This sheet is a map of that ground, written as interview questions.

2. Is Python interpreted or compiled?

Python is an interpreted language. An interpreted language runs its code line by line, through a program called an interpreter. A compiled language is turned into machine code first, and that machine code runs later.

In practice, Python sits between the two. The interpreter first turns your source into a compact form called bytecode. Then it runs that bytecode. You never see the middle step, because Python handles it for you.

The program below shows the running order. Python runs the first line, then the second. There is no separate build step to wait for. The Python Syntax lesson in the Beginner course shows the same top-to-bottom order.

print(2 + 3)
print("Python runs this line after the one above it")

Output:
5
Python runs this line after the one above it

3. How do you print output in Python?

Use the print function. A function is a named block of code that does one job. The print function writes its arguments to the screen, with a space between each one.

Two small settings change how print behaves. The sep setting chooses what goes between the arguments. The end setting chooses what comes after the last one. By default, print ends with a new line.

The program below prints three colours joined by dashes, then prints two words on one line. The Python Output lesson in the Beginner course covers print in full.

print("red", "green", "blue", sep="-")
print("one", end=" ")
print("two")

Output:
red-green-blue
one two

4. What are variables, and is Python dynamically typed?

A variable is a name that holds a value. You create one by writing a name, an equals sign, and a value. Python stores the value and remembers it under that name.

Python is dynamically typed. A type is the kind of a value, such as a number or a piece of text. In Python, a name is not tied to one type. The same name can hold a number now and a piece of text later.

The program below prints a value, then its type, then the same name holding a different type. The type function reports the kind of a value. The Python Variables and Python Data Types lessons in the Beginner course teach both ideas.

value = 42
print(value, type(value))
value = "forty-two"
print(value, type(value))

Output:
42 <class 'int'>
forty-two <class 'str'>

5. How does indentation work in Python?

Indentation is the spaces at the start of a line. In Python, indentation is not decoration. It shows which lines belong together inside a block, such as the body of an if statement.

A block starts after a line that ends with a colon. Every line in the block is indented by the same amount, usually four spaces. A line that returns to the earlier indent ends the block.

The program below prints two lines only when the temperature is above 30. The last line is not indented, so it always runs. The Python If Statement lesson in the Beginner course works through the same pattern.

temperature = 31
if temperature > 30:
    print("It is hot outside.")
    print("Drink some water.")
print("Done.")

Output:
It is hot outside.
Drink some water.
Done.

6. How do you take input from the user?

Use the input function. It shows a prompt, waits for the user to type, and returns what was typed. It always returns a string, even when the user types digits.

That last point catches beginners. Typing 42 gives the string "42", not the number 42. To do arithmetic with it, convert it first with int or float. The Python Casting lesson in the Beginner course covers those conversions.

The program below was run with Maya typed at the prompt. The Python User Input lesson in the Beginner course shows the same call.

name = input("What is your name? ")
print(f"Hello, {name}.")

Output:
What is your name? Hello, Maya.

7. What are comments, and how do you write them?

A comment is a note inside the code that Python ignores. Comments explain why code does something. They never change what the code does.

A comment starts with a hash sign. Everything after the hash on that line is ignored. A comment can fill a whole line, or sit after code on the same line.

The program below adds two numbers. The comments say what is happening. The code itself is one line. The Python Comments lesson in the Beginner course covers the same rule.

# This line is a comment. Python ignores it.
total = 4 + 5  # A comment can sit after code too.
print(total)

Output:
9

8. What is the difference between Python 2 and Python 3?

Python 3 is the current version of the language. Python 2 reached the end of its supported life in 2020. New code is written in Python 3, and interviewers expect Python 3 answers.

The most visible change is print. In Python 2, print was a statement, written as print "hello". In Python 3, print is a function, written as print("hello"). Code written the old way does not run in Python 3.

Other changes run deeper. Python 3 treats text as Unicode by default, so it handles languages beyond English cleanly. Division changed too: in Python 3, 3 / 2 gives 1.5, while in Python 2 it gave 1. The Python Installation lesson in the Beginner course shows how to check which version you have.

9. What data types does Python have?

A data type is the kind of a value. The common built-in types are int for whole numbers, float for numbers with a decimal point, str for text, bool for True and False, and NoneType for the single value None.

Python also has collection types. A list holds an ordered group of values. A tuple holds an ordered group that cannot change. A set holds unique values with no order. A dict holds pairs of keys and values.

The program below prints each value beside its type. The type function reports the kind of any value. The Python Data Types lesson in the Beginner course works through the same list.

values = [42, 3.5, "hello", True, None, [1, 2], {"a": 1}]
for value in values:
    print(value, type(value))

Output:
42 <class 'int'>
3.5 <class 'float'>
hello <class 'str'>
True <class 'bool'>
None <class 'NoneType'>
[1, 2] <class 'list'>
{'a': 1} <class 'dict'>

10. What is the difference between a list and a tuple?

A list is a collection you can change. You can add items, remove items, and replace items. A tuple is a collection you cannot change. Once a tuple is made, its items stay as they are.

That single difference decides which one to use. Use a list for a collection that grows or changes, such as a list of names. Use a tuple for a fixed group, such as the coordinates of a point.

The program below adds a colour to a list, then tries to change a tuple. The tuple refuses, and the error names the rule. The Python Lists and Python Tuples lessons in the Beginner course teach both types.

colours = ["red", "green"]
colours.append("blue")
print(colours)
point = (3, 4)
try:
    point[0] = 9
except TypeError as error:
    print("Tuple error:", error)

Output:
['red', 'green', 'blue']
Tuple error: 'tuple' object does not support item assignment

11. How do you slice a list or a string?

Slicing takes a section out of a sequence. A sequence is a value with an order, such as a list or a string. A slice is written with square brackets and a colon: start, stop, and an optional step.

Positions start at zero. The start position is included, and the stop position is not. A negative position counts from the end, so -1 is the last item. A step of -1 walks backwards.

The program below slices the word python and a short list of numbers. The Python String Slicing and Python Access List Items lessons in the Beginner course cover the same moves.

word = "python"
print(word[0:2])
print(word[2:])
print(word[::-1])
numbers = [10, 20, 30, 40, 50]
print(numbers[1:4])
print(numbers[-2:])

Output:
py
thon
nohtyp
[20, 30, 40]
[40, 50]

12. What is a list comprehension?

A list comprehension builds a list in one line. It is a short way of writing a loop that makes a list. The pattern is an expression, then for, then a source, then an optional condition.

Read it from right to left. The for part names the source. The condition keeps only the values that pass. The expression at the front says what goes into the new list.

The program below builds squares, then filters the even numbers from zero to nine. The Python List Comprehension lesson in the Beginner course teaches the same pattern with more examples.

squares = [n * n for n in range(6)]
print(squares)
evens = [n for n in range(10) if n % 2 == 0]
print(evens)

Output:
[0, 1, 4, 9, 16, 25]
[0, 2, 4, 6, 8]

13. How do you remove duplicates from a list?

A duplicate is a value that appears more than once. There are two good ways to remove duplicates, and they differ in one respect: whether the original order survives.

The first way keeps order. Turning the list into a dict and back uses the fact that a dictionary cannot hold the same key twice. The first appearance of each value wins, and the order stays.

The second way is shorter but loses order. A set cannot hold duplicates either, so converting to a set and sorting gives the same values in sorted order. The Python Sets lesson in the Beginner course explains why a set drops repeats.

names = ["ana", "ben", "ana", "cleo", "ben"]
print(list(dict.fromkeys(names)))
print(sorted(set(names)))

Output:
['ana', 'ben', 'cleo']
['ana', 'ben', 'cleo']

14. How do you sort a list of dictionaries?

Use the sorted function with a key. The key is a helper that picks, for each item, the value sorted should compare. For a list of dictionaries, that helper usually pulls one field out of each dictionary.

A lambda is the usual way to write that helper. It is a nameless function squeezed into one line. The lambda here takes one dictionary and returns its age.

The program below sorts three people by age, youngest first. The Python Sorting With a Key lesson in the Intermediate course teaches the same pattern, and question 23 explains lambdas.

people = [{"name": "Ana", "age": 34}, {"name": "Ben", "age": 28}, {"name": "Cleo", "age": 41}]
by_age = sorted(people, key=lambda person: person["age"])
for person in by_age:
    print(person["name"], person["age"])

Output:
Ben 28
Ana 34
Cleo 41

15. What is a dictionary, and how do you loop over it?

A dictionary holds key-value pairs. A key names one slot in the dictionary, and the value is whatever sits in that slot. You fetch a value by naming its key, the way you would look a word up in a glossary.

The items method gives back the pairs one at a time. A for loop over items gives each key and its value together. That is the usual way to walk through a whole dictionary.

The program below prints three scores, then asks for a missing name. The get method returns a fallback instead of raising an error when the key is absent. The Python Dictionaries and Python Loop Dictionaries lessons in the Beginner course cover both moves.

scores = {"maya": 82, "leo": 95, "ana": 82}
for name, score in scores.items():
    print(name, score)
print(scores.get("tom", "no score"))

Output:
maya 82
leo 95
ana 82
no score

16. What is a set, and when do you use one?

A set holds values once each, and keeps no order among them. Each value appears a single time. Adding a value that is already there changes nothing.

Sets shine at two jobs: testing membership and comparing groups. Membership is a quick check, because a set is built for lookups. Comparing groups means finding what two sets share, what either holds, and what only one holds.

The program below shows the three comparisons. The ampersand gives the overlap, the pipe gives everything, and the minus gives what is only in the first set. The Python Set Operations lesson in the Beginner course works through the same three.

a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
print(sorted(a & b))
print(sorted(a | b))
print(sorted(a - b))

Output:
[3, 4]
[1, 2, 3, 4, 5, 6]
[1, 2]

17. How are strings different from lists?

Strings are immutable. Immutable means a value cannot be changed after it is made. Lists are mutable, so their items can be replaced. Strings cannot be changed in place.

That does not mean strings are frozen. Methods such as capitalize return a new string with the change applied. The original string stays untouched. That is the pattern to remember: a string method gives back a new string.

The program below tries to change one letter of a word, and the error names the rule. Then capitalize returns a new word, and the original is still lower case. The Python Strings and Python Modify Strings lessons in the Beginner course teach the same idea.

word = "python"
try:
    word[0] = "P"
except TypeError as error:
    print("String error:", error)
print(word.capitalize())
print(word)

Output:
String error: 'str' object does not support item assignment
Python
python

18. What does == do, and how is it different from is?

The == operator compares values. It asks whether two values hold the same contents. The is operator compares identity. It asks whether two names point to the very same object in memory.

Two separate lists with the same items are equal, so == gives True. But they are two different objects, so is gives False. Assigning one name to another makes both names point to one object, and then is gives True.

The program below shows all three cases. It also shows that None is checked with is, never with ==. The Python Identity & Membership Operators lesson in the Beginner course teaches the same distinction.

a = [1, 2, 3]
b = [1, 2, 3]
print(a == b)
print(a is b)
c = a
print(a is c)
print(None is None)

Output:
True
False
True
True

19. What is the difference between a shallow copy and a deep copy?

A copy is a second object with the same contents. A shallow copy copies the outer container but shares the inner objects. A deep copy copies everything, all the way down.

The difference only shows when the original holds other mutable values, such as lists inside a list. Changing an inner list through a shallow copy changes the original too, because both copies share that inner list. A deep copy has its own inner lists, so it cannot affect the original.

The program below changes a deep copy first, and the original does not move. Then it changes a shallow copy, and the original moves with it. The Python Copying in Depth lesson in the Advanced course covers both kinds of copy.

import copy
original = [[1, 2], [3, 4]]
deep = copy.deepcopy(original)
deep[0].append(77)
print("after changing the deep copy:", original)
shallow = copy.copy(original)
shallow[0].append(99)
print("after changing the shallow copy:", original)

Output:
after changing the deep copy: [[1, 2], [3, 4]]
after changing the shallow copy: [[1, 2, 99], [3, 4]]

20. What is the mutable default argument trap?

A default argument is a value a parameter takes when the caller passes nothing. The trap is that Python creates that default value once, when the function is defined, and reuses the same object on every call.

For a number or a string, that reuse is harmless, because those values cannot change. For a list, it is a bug. Each call appends to the same list, so items from earlier calls are still there.

The program below calls the function twice with no basket, and the second call sees the apple from the first. Passing a fresh list avoids it. The Python The Mutable Default Trap lesson in the Intermediate course works through the same example and the fix.

def add_item(item, basket=[]):
    basket.append(item)
    return basket

print(add_item("apple"))
print(add_item("pear"))
print(add_item("plum", []))

Output:
['apple']
['apple', 'pear']
['plum']

21. How do you define a function, and what does return do?

Define a function with def, a name, and parentheses holding its parameters. A parameter is a name the function uses for a value passed in. The body is indented under the def line.

The return statement sends a value back to the caller and ends the function. A function without return sends back None. Calling a function runs its body with the values you pass.

The program below defines a function that returns an area, then calls it twice. The Python Functions and Python Return Values lessons in the Beginner course teach both parts.

def area(width, height):
    return width * height

print(area(4, 5))
print(area(3, 3))

Output:
20
9

22. What are *args and **kwargs?

The star forms let a function accept a flexible number of arguments. The single star, *args, gathers extra positional arguments into a tuple. The double star, **kwargs, gathers extra keyword arguments into a dictionary.

Positional arguments are matched by position. Keyword arguments are matched by name. A function that takes *args and **kwargs can accept any combination of the two, which is useful for wrappers and for functions that pass arguments along.

The program below passes two tags and two named details. The tags arrive as a tuple, and the details arrive as a dictionary. The Python Arbitrary Arguments lesson in the Beginner course covers both forms.

def describe(name, *tags, **details):
    print(name, tags, details)

describe("Ana", "reader", "early-riser", city="Leeds", age=34)

Output:
Ana ('reader', 'early-riser') {'city': 'Leeds', 'age': 34}

23. What is a lambda?

A lambda builds a tiny unnamed function in a single line. It takes its arguments after the word lambda, then an expression that gives the result. A lambda holds no statements and no return keyword; the expression is the result.

Lambdas are used where a small function is needed once, such as a sort key or a mapping. For anything longer than one expression, a named function with def is clearer.

The program below sorts words by length with a lambda, then doubles three numbers with map and a lambda. The Python Lambda Functions lesson in the Beginner course and the Python map() and filter() lesson in the Intermediate course both use the same pattern.

words = ["banana", "fig", "cherry"]
print(sorted(words, key=lambda word: len(word)))
doubled = list(map(lambda n: n * 2, [1, 2, 3]))
print(doubled)

Output:
['fig', 'banana', 'cherry']
[2, 4, 6]

24. What is scope, and what does LEGB mean?

Scope is the part of a program where a name is visible. A name defined inside a function is local to that function. A name defined outside any function is global, and visible everywhere.

LEGB is the order Python searches for a name: Local, then Enclosing, then Global, then Built-in. Local is the current function. Enclosing is a function wrapped around it. Global is the module level. Built-in is names like print and len.

The program below defines count twice, once outside and once inside a function. Each print sees the count in its own scope, so the two prints differ. The Python Scope lesson in the Beginner course explains the same rule.

count = 10

def show():
    count = 20
    print("inside:", count)

show()
print("outside:", count)

Output:
inside: 20
outside: 10

25. What is a closure?

A closure is a function that remembers the variables of the function that made it. The outer function returns the inner function, and the inner function keeps hold of the outer function's names.

The nonlocal statement lets the inner function change a variable from the outer function. Without it, an assignment inside the inner function would make a new local name instead.

The program below builds a counter. Each call adds one to a total that lives in the outer function, and the total survives between calls. The Python Closures lesson in the Advanced course teaches the same pattern.

def make_counter():
    total = 0
    def count():
        nonlocal total
        total += 1
        return total
    return count

counter = make_counter()
print(counter())
print(counter())
print(counter())

Output:
1
2
3

26. What is a decorator?

A decorator is a function that takes another function and returns a changed version of it. The @ sign above a function applies the decorator at the moment the function is defined.

Decorators add behaviour around a function without rewriting it. Logging, timing, and access checks are the classic uses. The wrapper inside the decorator usually accepts *args and **kwargs, so it works with any function.

The program below wraps a greeting so its result comes back in upper case. The wrapper calls the original function, then changes the result. The Python Decorators lesson in the Advanced course builds the same idea step by step.

def shout(func):
    def wrapper(*args, **kwargs):
        result = func(*args, **kwargs)
        return result.upper()
    return wrapper

@shout
def greet(name):
    return f"hello, {name}"

print(greet("Ana"))

Output:
HELLO, ANA

27. What is recursion, and when does it stop?

Recursion is a function calling itself. A recursive function solves a smaller version of its own problem, then combines the result. Every recursive function needs a base case, a simplest input that returns without calling itself again.

Without a base case, the function calls itself forever until Python stops it with a RecursionError. With a base case, the calls unwind one by one, each returning its result to the caller above it.

The program below computes a factorial. The base case is n at or below 1, which returns 1. The Python Recursion lesson in the Beginner course and Python Recursion in Depth in the Advanced course both use the same example.

def factorial(n):
    if n <= 1:
        return 1
    return n * factorial(n - 1)

print(factorial(5))
print(factorial(0))

Output:
120
1

28. What is a class, and what is an object?

A class is a plan for making objects. An object is one thing made from that plan. A class defines the data an object holds and the actions it can do. An object is a single example with its own data.

The __init__ method runs when an object is made. It sets up the object's starting data. The word self inside a method means the object the method was called on.

The program below defines a Dog class, makes one dog called Rex, and asks it to bark. The Python Classes & Objects and Python The __init__ Method lessons in the Beginner course teach both ideas.

class Dog:
    def __init__(self, name):
        self.name = name
    def bark(self):
        return f"{self.name} says woof"

rex = Dog("Rex")
print(rex.bark())
print(rex.name)

Output:
Rex says woof
Rex

29. What does self do, and why does each object keep its own data?

Self is the first parameter of every method. It refers to the object the method is running on. When you call first.add(), Python passes first in as self.

Because each object stores its own data under self, two objects made from the same class do not share their state. Changing one leaves the other untouched.

The program below makes two counters, adds to the first one twice, and prints both totals. The first reads 2 and the second reads 0. The Python Class & Instance Attributes lesson in the Beginner course explains the same split.

class Counter:
    def __init__(self):
        self.total = 0
    def add(self):
        self.total += 1

first = Counter()
second = Counter()
first.add()
first.add()
print(first.total, second.total)

Output:
2 0

30. How does inheritance work?

Inheritance lets a class take behaviour from another class. The child class is written with the parent class in parentheses. The child gains the parent's methods and can replace any of them.

Replacing a method is called overriding. The child writes its own version with the same name, and that version runs instead. Code that expects the parent still works with the child, because the child is a kind of the parent.

The program below defines an Animal that makes a plain sound, then a Cat that overrides it with a meow. The isinstance check confirms the cat is still an animal. The Python Inheritance lesson in the Beginner course covers the same pattern.

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

class Cat(Animal):
    def sound(self):
        return "meow"

pet = Cat()
print(pet.sound())
print(isinstance(pet, Animal))

Output:
meow
True

31. What is the difference between __str__ and __repr__?

Both methods turn an object into text, but for different readers. The __str__ method is for people. It returns a friendly reading of the object. The __repr__ method is for programmers. It returns a precise reading that ideally shows how to rebuild the object.

Print and str use __str__. The repr function and the interactive prompt use __repr__. When an object sits inside a list, the list shows its __repr__, because a list is a programmer's view.

The program below prints a point three ways. The first two lines differ, and the list shows the __repr__ form. The Python __str__ and __repr__ lesson in the Advanced course teaches the same split.

class Point:
    def __init__(self, x, y):
        self.x, self.y = x, y
    def __str__(self):
        return f"({self.x}, {self.y})"
    def __repr__(self):
        return f"Point({self.x}, {self.y})"

p = Point(3, 4)
print(p)
print(repr(p))
print([p])

Output:
(3, 4)
Point(3, 4)
[Point(3, 4)]

32. What are class attributes and instance attributes?

An instance attribute belongs to one object. It is set inside __init__ with self, and each object has its own value. A class attribute belongs to the class itself. It is set in the class body, and every object reads the same value.

Changing a class attribute through the class changes what every object sees. Changing an instance attribute on one object affects only that object. That split is the whole difference.

The program below gives two teams a shared sport and their own names. Changing the sport through the class moves both teams. Renaming one team moves only that team. The Python Shared Class Attributes lesson in the Intermediate course works through the same split.

class Team:
    sport = "football"
    def __init__(self, name):
        self.name = name

a = Team("Rovers")
b = Team("United")
Team.sport = "rugby"
print(a.sport, b.sport)
a.name = "Rovers FC"
print(a.name, b.name)

Output:
rugby rugby
Rovers FC United

33. What is polymorphism in practice?

Polymorphism means different objects can be used through the same interface. An interface is a shared set of method names. Code that calls one of those methods does not need to know which kind of object it has.

In Python, polymorphism comes from duck typing. Duck typing means an object is judged by the methods it has, not by the class it came from. If it has a speak method, the loop can call speak on it.

The program below loops over a duck and a robot duck. Both answer speak, and the loop treats them the same. The Python Polymorphism lesson in the Beginner course teaches the same idea.

class Duck:
    def speak(self):
        return "quack"

class RobotDuck:
    def speak(self):
        return "beep-quack"

for bird in [Duck(), RobotDuck()]:
    print(bird.speak())

Output:
quack
beep-quack

34. What is the difference between an iterable and an iterator?

An iterable is a value you can loop over. A list is an iterable. An iterator is the object that does the looping, handing out one value at a time. The iter function turns an iterable into an iterator.

The next function asks an iterator for its next value. When the values run out, next raises StopIteration. A for loop handles that for you, which is why you rarely call next yourself.

The program below takes an iterator from a list, pulls two values out by hand, then turns the rest back into a list. One value is left at that point. The Python Iterators lesson in the Beginner course and Python The Iterator Protocol in the Advanced course both teach the same split.

numbers = [10, 20, 30]
it = iter(numbers)
print(next(it))
print(next(it))
print(list(it))

Output:
10
20
[30]

35. What is a generator, and what does yield do?

A generator is a function that produces values one at a time. The yield keyword pauses the function and hands a value to the caller. The next call resumes the function right where it stopped.

A generator does not build its whole result up front. It makes each value only when asked. That is why generators are used for long sequences and for streams of data that would not fit in memory all at once.

The program below counts down from three. Each loop step wakes the generator, takes one value, and pauses it again. The Python Generators lesson in the Advanced course teaches the same pattern.

def countdown(n):
    while n > 0:
        yield n
        n -= 1

for value in countdown(3):
    print(value)

Output:
3
2
1

36. When would you use a generator expression instead of a list comprehension?

A generator expression looks like a list comprehension with round brackets instead of square ones. The difference is when the values are made. A list comprehension makes them all at once. A generator expression makes each one on demand.

Use a generator expression when you only need to pass through the values once, such as summing them or feeding them to a function. Use a list comprehension when you need the values again, or need to index them, or need their length.

The program below measures both for a thousand squares. The list takes thousands of bytes, because it holds every square. The generator takes a small fixed amount, because it holds only its place. The Python Generator Expressions lesson in the Advanced course covers the same trade-off.

import sys
squares_list = [n * n for n in range(1000)]
squares_gen = (n * n for n in range(1000))
print(sys.getsizeof(squares_list), "bytes for the list")
print(sys.getsizeof(squares_gen), "bytes for the generator")
print(sum(n * n for n in range(5)))

Output:
8856 bytes for the list
200 bytes for the generator
30

37. How do you handle errors with try and except?

A try block holds code that might fail. An except block holds the code that runs when a named error happens. An error in Python is called an exception.

Catch the specific exception you expect, such as ZeroDivisionError. Catching every exception hides mistakes you did not expect, including typing errors in your own code. A bare except is a habit to avoid.

The program below divides two numbers. The first call succeeds. The second would divide by zero, so the except block returns a message instead. The Python Try Except lesson in the Beginner course teaches the same shape.

def divide(a, b):
    try:
        return a / b
    except ZeroDivisionError:
        return "cannot divide by zero"

print(divide(10, 2))
print(divide(10, 0))

Output:
5.0
cannot divide by zero

38. When should you raise your own exception?

Raise an exception when the caller has broken a rule your function cannot fix. The raise statement creates the exception, and the function stops at that point. The caller decides whether to catch it.

Choose the built-in exception that fits. A ValueError fits a value that is the wrong kind of value, such as a negative age. A TypeError fits a value of the wrong type. Raising a clear error beats returning a special value that the caller might ignore.

The program below accepts a valid age and rejects a negative one with a message. The Python Raise Exceptions lesson in the Beginner course and Python Custom Exceptions in the Advanced course both cover the same habit.

def set_age(age):
    if age < 0:
        raise ValueError("age cannot be negative")
    return age

print(set_age(34))
try:
    set_age(-3)
except ValueError as error:
    print("Error:", error)

Output:
34
Error: age cannot be negative

39. What is EAFP, and how is it different from LBYL?

EAFP stands for Easier to Ask Forgiveness than Permission. It means try the action first, and handle the failure if it happens. LBYL stands for Look Before You Leap. It means check first, then act.

EAFP is the usual Python style. It keeps the code short, and it avoids a race between the check and the action, where the situation changes in between. LBYL is the right choice when the failure is expensive, or when the check is cheap and the action is not.

The program below looks up a missing name both ways. Both print the same message. The Python EAFP: Ask Forgiveness First lesson in the Intermediate course works through the same comparison.

scores = {"ana": 82, "leo": 95}
if "tom" in scores:
    print(scores["tom"])
else:
    print("tom has no score yet (checked first)")
try:
    print(scores["tom"])
except KeyError:
    print("tom has no score yet (asked forgiveness)")

Output:
tom has no score yet (checked first)
tom has no score yet (asked forgiveness)

40. What does the with statement do for files?

The with statement opens a file and closes it for you, even when something goes wrong. Closing a file releases it, and flushes any writing that is still waiting. Forgetting to close a file is a common source of lost writes.

Open a file with a mode. The w mode writes, and creates the file if it is missing. The r mode reads, and is the default. A file opened for reading must already exist.

The program below writes two lines, then opens the file again and prints what it holds. The Python Open & Close Files and Python Write to Files lessons in the Beginner course teach the same pattern.

with open("notes.txt", "w") as f:
    f.write("first line\nsecond line\n")
with open("notes.txt") as f:
    print(f.read())

Output:
first line
second line

41. How do you read a file line by line?

Loop over the file object directly. A file object gives its lines one at a time, and never loads the whole file into memory. That matters for large files, such as logs.

The enumerate function adds a counter to any loop. It gives each item a number alongside the value. Starting the count at one gives human line numbers instead of zero-based positions.

The program below writes three fruit names, then reads them back numbered. The strip call removes the newline at the end of each line. The Python Reading Files Line by Line lesson in the Intermediate course teaches the same loop.

with open("notes.txt", "w") as f:
    f.write("apples\nbananas\ncherries\n")
with open("notes.txt") as f:
    for number, line in enumerate(f, start=1):
        print(number, line.strip())

Output:
1 apples
2 bananas
3 cherries

42. How do modules and packages work?

A module is a Python file. Importing it runs its top-level code once and makes its names available. A package is a folder of modules, with an __init__.py file marking it as a package.

A module often needs to know whether it is being run or imported. The __name__ variable answers that. It holds "__main__" when the file is run as a script, and the module name when it is imported.

The program below prints only when run as a script. Importing the same file would print nothing, because __name__ would not be "__main__". The Python Modules lesson in the Beginner course and Python The __main__ Guard in the Advanced course both teach the same guard.

def main():
    print("running as a script")

if __name__ == "__main__":
    main()

Output:
running as a script

43. What are virtual environments, and why use one?

A virtual environment is a private copy of Python for one project. It holds its own installed packages, separate from every other project on the machine. The venv module creates one, and pip installs packages into it.

Without one, every project shares the same packages. Two projects that need different versions of the same package then fight. With one, each project keeps the versions it was built against.

The usual commands are python3 -m venv .venv to create one, then activating it before installing anything. The Python Virtual Environments lesson in the Beginner course and Python Virtual Environments in Depth in the Advanced course both walk through the same steps.

44. How do you test a small function with unittest?

The unittest module is Python's built-in testing framework. A test case is a class that inherits from unittest.TestCase. Each test is a method whose name starts with test, and each check is an assert method such as assertEqual.

Run the file, and unittest reports each test with a dot for a pass. A failure prints the test name and the values that disagreed. Tests turn a guess about your code into a check you can repeat.

The program below tests a doubling function with two inputs. The output shows one test ran and passed. The Python Testing a Small Module lesson in the Intermediate course and Python unittest Basics in the Advanced course both teach the same shape.

import unittest

def double(n):
    return n * 2

class TestDouble(unittest.TestCase):
    def test_double(self):
        self.assertEqual(double(3), 6)
        self.assertEqual(double(0), 0)

if __name__ == "__main__":
    unittest.main()

Output:
.
----------------------------------------------------------------------
Ran 1 test in 0.000s

OK

45. How do you read a traceback?

A traceback is the report Python prints when an uncaught exception stops a program. Read it from the bottom up. The last line names the exception and its message. The lines above it show the chain of calls that led there.

Each frame in the chain names a file, a line number, and a function. The innermost frame, at the bottom of the chain, is where the error actually happened. The frames above it show how the program got there.

The program below divides by zero inside a helper, called from another helper. The traceback lists both helpers, and the last line names the error. The Python Reading a Traceback lesson in the Intermediate course teaches the same bottom-up reading, and the Python Debugging With pdb lesson shows how to step through a live program.

def level_two():
    return 1 / 0

def level_one():
    return level_two()

level_one()

Output:
Traceback (most recent call last):
  File "<string>", line 7, in <module>
  File "<string>", line 5, in level_one
  File "<string>", line 2, in level_two
ZeroDivisionError: division by zero

46. What does the logging module give you that print does not?

The logging module records events with a level and a format. A level is a severity, such as INFO for normal news and WARNING for something odd. The format decides what each line looks like.

Print has no levels and no off switch. To silence prints, you must remove them. Logging can be turned up or down in one place, sent to a file instead of the screen, and kept in the code permanently without cluttering normal output.

The program below logs three events. The middle one is a warning, and the format puts the level first. The Python Logging Basics lesson in the Advanced course teaches the same setup.

import logging
logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")
logging.info("starting the report")
logging.warning("one row was missing a date")
logging.info("report finished")

Output:
INFO: starting the report
WARNING: one row was missing a date
INFO: report finished

47. What is the GIL, and when do threads help?

The GIL is the Global Interpreter Lock. It is a lock in CPython, the usual Python implementation, that lets only one thread run Python code at a time. Threads still take turns quickly, so they work well for waiting, but not for heavy number crunching.

Threads help when a program spends its time waiting: fetching pages, reading files, or waiting on a network. While one thread waits, another can run. For work that is pure calculation, threads do not speed things up, and processes are the better tool.

The program below runs a small job across a pool of two threads. The result is the same list of squares in the same order. The Python The GIL & Choosing Threads and Python ThreadPoolExecutor lessons in the Advanced course explain when to pick threads, processes, or asyncio.

from concurrent.futures import ThreadPoolExecutor

def square(n):
    return n * n

with ThreadPoolExecutor(max_workers=2) as pool:
    print(list(pool.map(square, [1, 2, 3, 4])))

Output:
[1, 4, 9, 16]

48. What is asyncio, and when would you use it?

Asyncio is Python's built-in way to write code that waits without blocking. An async function can pause at an await point while it waits, and other work runs in the meantime. One thread can then juggle many waiting jobs.

Use asyncio for programs that wait on many things at once, such as fetching dozens of pages or serving many connections. It is not a way to speed up calculation. For that, use processes.

The program below runs two small async jobs together with gather and prints both results. The Python Asyncio Basics lesson in the Advanced course teaches the same pattern, and Python Asyncio Tasks & Gather covers gather in full.

import asyncio

async def fetch(name):
    await asyncio.sleep(0)
    return f"done: {name}"

async def main():
    results = await asyncio.gather(fetch("a"), fetch("b"))
    print(results)

asyncio.run(main())

Output:
['done: a', 'done: b']

49. How would you count words in a text file?

Counting words is three small steps: split the text into words, count them, and report the most common. The Counter class from the collections module does the counting in one call.

The split method breaks text on whitespace and returns a list of words. Counter turns that list into a dictionary of word counts. The most_common method returns the top entries in order.

The program below counts the words in one sentence. The word the appears three times, cat twice, and the rest once. The Python Counting With Dictionaries lesson in the Intermediate course and the Python Project: Text Report in the Beginner course both build the same counter.

from collections import Counter
text = "the cat sat on the mat and the cat slept"
counts = Counter(text.split())
for word, count in counts.most_common(3):
    print(word, count)

Output:
the 3
cat 2
sat 1

50. What should you learn after this sheet?

Work through the answers you missed, in the lessons they name. The gaps matter more than the ones you already knew. A missed question on closures means the Python Closures lesson in the Advanced course. A missed question on copying means Python Copying in Depth.

Then build something that forces the ideas together. The Advanced course ends with five projects: a command-line tool, a data pipeline from CSV to SQLite to JSON, a concurrent fetcher, a file organiser, and a tested little library. Each one uses a dozen ideas from this sheet at once.

One honest limit remains. This sheet does not cover pandas or numpy. Both are taught in the Pandas course on this site, which has 50 lessons. If your interviews are for data-science roles, work through that course next, on top of the Python here. For general Python roles, this sheet and the 270 lessons behind it cover the ground interviewers actually ask about.

Questions readers ask

How should I prepare for a Python interview in one week?

Work through this sheet one topic at a time, saying each answer aloud before reading it, and run every program yourself. Start with data structures and functions, then classes and generators, then files and exceptions. Redo the questions you missed the next day. One week of daily practice beats one long night of reading.

Must I learn all fifty answers by heart?

No. Learn the core patterns instead: mutability, slicing, comprehensions, closures, decorators, generators, and the try and except shape. Nearly every question here is one of those patterns wearing different details. If you can explain mutability, write a decorator, and build a generator without looking, the remaining answers follow from those.

Which Python version should I practise in?

Python 3, the current version. Every program on this page was run on Python 3.12.3. Python 2 reached the end of its supported life in 2020, and its answers, such as print as a statement, no longer apply.

What does this sheet not cover?

Pandas and numpy, the two libraries most data-science interviews lean on. This sheet does not cover them, but the Pandas course on this site teaches both, in 50 lessons. It also skips frameworks such as Django and Flask, which are separate topics. Everything else here is backed by a lesson on this site.