# Top 50 Python Interview Questions of 2023 (with Answers)

Are you preparing for a job interview or an exam that involves knowledge about Python?

Or do you want to quickly go through common topics of Python?

Here is a list of 50 Python interview questions and answers. The list is in no particular order.

I hope you enjoy it.

## 1. Name Differences Between a List and a Tuple

A list and a tuple have some things in common. One might even imagine they are almost the same type. But this is not the case.

Let’s take a look at the key differences between tuples and lists in short:

• Mutable
• Higher memory consumption
• A lot of built-in methods are available
• Slower iteration
• Better for operations like insertion and deletion

• Immutable
• Lower memory consumption
• A small number of built-in methods available
• Faster iteration
• Better for accessing elements

## 2. What Does the Range() Function Do?

The built-in `range()` function creates a range of integers.

Here is a couple of use cases:

```# 0,1,2,3,4,5,6,7,8,9
nums1 = range(10)

# prints 0,1,2,3,4
for num in range(5):
print(num)

# 10,11,12,13,14,15
nums2 = range(10,16)

# 10, 20, 30, 40, 50, 60, 70, 80, 90, 100
nums3 = range(10,110,10)```

## 3. How Does Map() Function Work?

`map()` function can be used to transform an iterable, such as a list, into another. The `map()` function returns a map object. This can be converted back to a list for example with the `list()` function.

For example, you can square a list of numbers by using a `map()` function and converting the result object to a list:

```numbers = [1, 2, 3, 4]
squared_numbers = map(lambda x: x ** 2, numbers)

print(list(squared_numbers))```

Output:

`[1, 4, 9, 16]`

## 4. What is the Difference between “is” and “==”?

• The `==` operator compares the equality of two values.
• The `is` operator checks if two variables point to the same memory address.

## 5. What is a Decorator?

Decorators provide a way to extend the functionality of a function or a class.

A simple example: Suppose you have a `divide()` function:

```def divide(x, y):
return x / y```

The problem is that dividing by `0` is illegal. And the function does not check if `y` is `0`.

You could fix this with an if-check. But for the sake of demonstration, let’s use a decorator.

1. Let’s implement the decorator. This function takes a function as its input and creates a new function with the extended behavior of checking against `0`.
```def guard_zero(operate):
def inner(x, y):
if y == 0:
print("Cannot divide by 0.")
return
return operate(x, y)
return inner```

2. Now you can decorate the original function:

```@guard_zero
def divide(x, y):
return x / y```

3. Now `divide()` function checks if the divisor is 0.

`print(divide(10,0))`

Output:

`Cannot divide by 0.`

## 6. How Does Reduce() Function Work?

The `reduce()` function applies a function to the elements of a list and accumulates the result. This function is defined in `functools` module. To use it, import it into your project first.

For example, let’s calculate the sum of a list of numbers using `reduce()`:

```from functools import reduce

nums = [1, 2, 3, 4, 5]
sum_nums = reduce(lambda x, y: x+y, nums)

print("The sum is {}".format(sum_nums))```

This works such that:

1. It starts by taking the first two elements of the list. It applies the given function to them and stores the result. In this case, it takes the sum of the two.
2. Then it picks the third element and applies the function to it and to the previous result.
3. It continues this until the end of the list.

## 7. How Does the Filter() Function Work?

The `filter()` function can be used to filter elements based on a condition. The filter function takes two arguments:

1. A lambda expression i.e., a function that is executed for each element in the list.

2. A list on which it is going to operate.

For example, let’s filter even numbers from a list:

```numbers = [1, 2, 3, 4, 5, 6]

# filter even numbers
even_nums = filter(lambda x: x % 2 == 0, numbers)

print(list(even_nums))```

Output:

`[2, 4, 6]`

## 8. What is the Difference Between Shallow Copy and a Deep Copy?

• In Python, a shallow copy is a “one-level-deep” copy. This means the copied object contains references to the children of the original object.
• A deep copy is an independent copy of the original object.

Here is an illustration:

Also, feel free to revise how variables are references to objects in Python.

## 9. What Does Any() Function Do?

The `any()` function returns `True` if any element of an iterable (such as a list) is `True`. If not, it returns `False`.

For instance:

```any([False, False, False]) # Returns False
any([True, False, False])  # Returns True```

## 10. What Does All() Function Do?

The `all()` function can be used to test if all the values in an iterable (such as a list) are `True`. For instance:

```any([False, False, False]) # Returns False
any([True, False, False])  # Returns False
any([True, True, True])    # Returns True```

## 11. What is the Difference Between a Method and a Function?

Both essentially do the same thing but calling one either depends on the context.

• A method is associated with an object/class.
• A function is not associated with an object/class.

Example of a function:

```def greet(name):
print("Hello, {}".format(name))```

Example of the same as a method:

```class Person:
def greet(self, name):
print("Hello, {}".format(name))```

In the above, both `greet()` method and the `greet()` function does the same thing.

The difference is the method is tied to a class whereas the function is independent of the context.

## 12. What Is the Output of the Following? Why?

```nums = [1, 2, 3]
copied_nums = nums

copied_nums = 1000

print(copied_nums)```

The output is:

`[1000, 2, 3]`

In Python, the `=` doesn’t create a copy of an object.

Instead, it creates a new variable that refers to the original object.

This means changing a value in the copy changes the value of the original object too.

Here is a simple illustration of what happens under the hood:

## 13. How Do You Reverse a List in Python?

You can reverse a list using the built-in `reverse()` method of a list.

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

Output:

`[1,2,3]`

## 14. What Does ‘self’ Mean in a Class?

The `self` parameter refers to the class instance itself. It can be used to access the properties that belong to the class.

For example:

```class Person:
age = 20
return self.age >= 18

person = Person()

Output:

`True`

Using `self` the class instance can access to its `age` property.

Side note: `self` does not need to be named `self`. It can be named anything you want as far as it’s the first parameter of any function of the class.

## 15. How to Concatenate a List in Python?

To concatenate two or more lists in Python, use the assignment operator.

For instance:

```nums1 = [1,2,3]
nums2 = [4,5,6]

allNums = nums1 + nums2

print(allNums)```

Output:

`[1, 2, 3, 4, 5, 6]`

## 16. What are Pickling and Unpickling Conceptually?

Pickling and unpickling serialize Python objects.

• Pickling is the process of converting Python objects into a byte stream
• Unpickling is the opposite of pickling

These techniques are used when storing objects in a file or in a database.

## 17. Are Dictionaries Faster to Lookup than Lists?

• A list lookup time is `O(n)`. This is because in the worst case the whole list needs to be iterated through before the value is found.
• A dictionary lookup time is `O(1)`. This is because a dictionary is a hash table.

In other words, dictionary-lookup is quicker than a list lookup.

## 18. What is a Module in Python?

A module is a Python file. It contains functions and global variables that can be used in your program. If you want to use a module, you need to import it to your program (using the `import` statement).

For example:

`import math`

## 19. What is a Package in Python?

A package is a directory that contains modules (see module above).

## 20. What is Considered a Library in Python?

A library is a publicly available package or a module.

## 21. Why Converting a List to a Set Removes Duplicates?

If you don’t care about your list’s ordering, you can remove duplicates by converting them to a set and then back to a list. For instance:

```nums = [1,2,1,2,2,2,1,2,3]
nums = list(set(nums))

print(nums)```

Output:

`[1,2,3]`

This is because a set is a unique collection of values. Thus it cannot hold duplicate values.

Under the hood, when you add a duplicate value to a set, it silently ignores it and remains unchanged.

## 22. Can You Swap Two Variables Without a Third?

This one is one of the classic Python interview questions.

Yes, by using tuple unpacking:

```a = 1
b = 2

a, b = b, a

print(a, b)```

Output:

`2 1`

## 23. What Are Comprehensions in Python?

Comprehensions are shorthands for writing a for loop in Python. Python supports four different comprehensions:

• List comprehensions
• Dictionary comprehensions
• Set comprehensions
• Generator comprehensions

For example, a list comprehension follows this syntax:

`newlist = [expression for item in iterable if condition == True]`

The other types of comprehensions look similar.

## 24. Why and When Use List Comprehensions?

A comprehension is meant to be used to make the code more clear and concise. It may be wise to use one when it can improve the code quality.

For instance, let’s create a list of even numbers from 0 to 9:

```even_nums = []
for number in range(10):
if number % 2 == 0:
even_nums.append(number)

print(even_nums)```

Output:

`[0, 2, 4, 6, 8]`

This for loop is quite simple to understand, yet it eats up some lines of code. You can achieve the same with one line of code by utilizing a list comprehension:

```even_nums = [number for number in range(10) if number % 2 == 0]
print(even_nums)```

Output:

`[0, 2, 4, 6, 8]`

## 25. What Does the Enumerate() Function Do?

Enumerate function couples a list with indexes.

```letters = ["a", "b", "c"]
indexed_letters = enumerate(letters)

print(list(indexed_letters))```

Output:

`[(0, 'a'), (1, 'b'), (2, 'c')]`

Using `enumerate()` is useful when looping a list and you need to keep track of the index of the elements.

For example, using `enumerate()` allows you to replace this:

```queue = ["Jack", "Ann", "Sofie"]

for i in range(len(queue)):
name = queue[i]
print("{} is at {}. position".format(name, i + 1))```

With this:

```queue = ["Jack", "Ann", "Sofie"]

for position, name in enumerate(queue):
print("{} is at {}. position".format(name, position + 1))```

To give the same result of:

```Jack is at 1. position
Ann is at 2. position
Sofie is at 3. position```

## 26. What Is the Itertools Module?

Itertools is a popular Python module. It has useful methods to perform tasks related to looping over iterables.

You can use Itertools for example to obtain the permutations of a group of values. Or you can create an infinite group of evenly spaced numbers.

As an example, you can use the Itertools to find all the permutations of a list:

```from itertools import permutations

a = [1,2,3]

perms = permutations(a)

print(list(perms))```

Output:

`[(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]`

## 27. What is the Difference between Pass, Continue, and Break Statements?

• `pass` means do nothing. This is used because you cannot create empty classes, methods, etc. in Python.
• `continue` stops the execution of the iteration of a loop and jumps to the next one.
• `break` stops the iteration of a loop and jumps out of it.

## 28. What is the Ternary Operator?

The ternary operator allows you to write one-liner if-else statements.

For instance:

```isReady = False

# A regular if-else
print("Yay")
else:
print("Nope")

# A neat little shorthand

But be careful with these and only use them to make your code cleaner. Don’t do it for the sake of reducing lines of code. Some prefer not to do this shorthand at all.

## 29. How Could You Simplify This?

`if n == 0 or n == 1 or n == 2 or n == 3 or n == 4 or n == 5:`

`if n in [0, 1, 2, 3, 4, 5]:`

## 30. Explain the Difference between Pop(), Remove(), and Del?

You can remove an element with a specific index using `pop()` method by passing it the index of the item.

```nums = [1, 2, 3]
nums.pop(1)

print(nums)```

Output:

`[1,3]`

You can use `remove()` to remove the first matching value of the argument in the list:

```nums = [1,1,2,2,3,3]
nums.remove(2)

print(nums)```

Output:

`[1,1,2,3,3]`

You can use `del` statement to remove an item at a specific index from a list.

For example:

```nums = [1,2,3]
del nums

print(nums)```

Output:

`[2,3]`

## 31. What is an Enumeration? How Do You Create One?

An enumeration is a group of symbolic names related to unique, constant values.

```from enum import Enum

class Color(Enum):
RED = 1
GREEN = 2
BLUE = 3```

## 32. How Do You Check If a Key Exists in a Dictionary?

```data = {"Ronaldo": 7, "Bale": 9, "Messi": 10}
print("Ronaldo" in data)```

Output:

`True`

## 33. What is a Docstring?

Docstring is used to document your Python code.

It is created with triple quotation marks. It also acts as the “multi-line comment”, even though that is not its original purpose.

To make it work as intended, you place the docstring as the first statement of a class, method, etc.

For instance, when you call the `help()` method you see the docstring of the function:

```def sum(num1, num2):
'''This is a method that sums up two numbers'''
return num1 + num2

help(sum)```

Output:

```Help on function sum in module __main__:

sum(num1, num2)
This is a method that sums up two numbers```

## 34. What Are Lambda Expressions?

In Python, lambda function is an anonymous function. It takes any number of arguments but contains a single expression.

As an example, here is a lambda that multiplies a number by three:

`lambda x : x * 3`

This isn’t useful as-is because there’s no way to call it. However, you can assign it to a variable and then call it like a regular function:

```mult3 = lambda x : x * 3
mult3(15.0) # returns 45```

You don’t actually need to assign a lambda to a variable. You can call it like this as well:

`(lambda x : x * 3)(15.0) # returns 45.0`

OutpuLambda functions are useful when the functionality is needed for a short period of time. In this case, you don’t want to waste resources by creating a separate method to do the job.

## 35. What Are F-String in Python?

Formatted string or F-string makes it possible to format strings like this:

```name = "Nick"
print(f"My name is {name}")```

Output:

`My name is Nick`

As opposed to the old-school approach using the `format` method:

```name = "Nick"
print("My name is {}".format(name))```

The f-string is more convenient especially when the number of embedded variables is big.

## 37. Python Lists vs. Numpy Arrays?

Briefly explain the differences between a regular Python list and a NumPy array.

A list is a resizeable collection. It may contain elements of different types. Python lists have limitations:

• A list cannot be treated as a vector in maths: It does not support elementwise addition and multiplication.
• Also, a list can contain different types of elements. This means Python needs to store type info for each element and handle the info when operating on each element. This means slower performance.

`NumPy` array is an efficient and more convenient way to store elements than a built-in list. It gives you vector and matrix operations. Also, the implementation of a `NumPy` array makes it more efficient. `NumPy` array:

• Takes less space.
• Is faster than a list.
• Provides functionality for performing linear algebra.

For example, let’s compare the efficiency of summing two lists of numbers using Python lists and `NumPy` arrays:

```import time
import numpy as np

N = 1000

def sum_lists():
t_0 = time.time()
nums1 = range(N)
nums2 = range(N)
sum_nums = [ nums1[i] + nums2[i] for i in range(N) ]
return time.time() - t_0

def sum_numpy_arrays():
t_0 = time.time()
nums1 = np.arange(N)
nums2 = np.arange(N)
sum_nums = nums1 + nums2
return time.time() - t_0

t1 = sum_lists()
t2 = sum_numpy_arrays()

print("Numpy was " + str(t1/t2) + " x faster!")```

Output (may vary):

`Numpy was 18.811023622047244 x faster!`

## 38. What is Pep8?

PEP or Python Enhancement Proposal defines a set of rules that specify how to format Python code.

Python linters use PEP guidelines to format/help formatting your code.

## 39. What is the __Init__() Method?

`__init__()` is a constructor method in Python. All classes need to have one.

This method is automatically called when a new instance of a class is created. Its purpose is to initialize/set up the instance.

For example, in a Person class, the initializer sets the name to the new class instance:

```class Person:
def __init__(self, name):
self.name = name

person = Person('Nick')
print(person.name)```

Output:

`Nick`

## 40. What Are Global Variables and Local Variables?

• A global variable is declared outside a function. A global variable can be accessed anywhere in the code.
• A local variable is declared inside a function. This variable can only be accessed within the function.

## 41. How Do You Handle Exceptions in Python?

Exception handling follows the try-except structure:

```try:
# try to run this block of code
except:
# do this if try block fails
finally:
# always run this block```

For example:

```try:
test = 1 + "one"
except:
print("Exception encountered! Default value will be used")
test = 10
finally:
print('This is always run')

print(test)```

Output:

```Exception encountered! Default value will be used
This is always run
10```

In the above, the `test = 1 + "one"` fails because summing a string and a number is not possible. The `except` block catches this error and runs some code.

With exception handling, your program does not crash. Instead, it resolves the error cases and continues to run.

## 42. How Do You Check If a Value Exists in a List?

```'A' in ['A','B','C']   # True
'A' in [1,2,3]         # False```

## 43. Can a Tuple Be a Dictionary Key?

Yes, a tuple can be used as a key in a dictionary. This is because a tuple is a hashable value.

## 44. What is the Join() Method? How Does It Work?

The `join()` method is a built-in string method. It connects elements of an iterable (such as a list) using a separator string.

For example, let’s join the characters of a list by separating them with an empty string:

```chars = ["H", "e", "l", "l", "o"]

word = "".join(chars)
print(word)```

Output:

`Hello`

The separator could be any string you like. For instance, to join using a dash `-` just do this:

```chars = ["H", "e", "l", "l", "o"]

word = "-".join(chars)
print(word)```

Output:

`H-e-l-l-o`

## 45. What is an Iterable?

An iterable is a Python object that is able to return its members one at a time. In other words, it allows looping.

Common examples of iterables are lists, dictionaries, and tuples.

## 46. What is an Iterator?

An iterator is an object that is used to iterate over iterables, such as lists, tuples, and dictionaries. It has a countable number of items.

An iterator conforms to the iterator protocol. This means it implements the methods `__iter__()` and `__next__()` to make it work.

For instance, let’s create an iterator for a tuple of fruits and use the `next()` function to print the fruits one by one:

```fruits = ("apple", "banana", "orange")
fruit_iterator = iter(fruits)

print(next(fruit_iterator))
print(next(fruit_iterator))
print(next(fruit_iterator))```

Output:

```apple
banana
orange```

## 47. What Is a Set?

Set is a built-in datatype in Python. It is a collection that is both unordered and unindexed. This means there is no order. Also, a set cannot hold duplicate values.

A set can be created by comma-separating elements inside curly brackets. For instance:

```num_set = {1,2,3,4,5}
print(num_set)```

Output:

`{1, 2, 3, 4, 5}`

## 48. How Do You Sort a List in a Reversed Order?

Sort a list using the `sort()` method of a list. To sort in a reversed order set the `reverse` parameter `True`:

```fruits = ["Banana", "Apple", "Cranberry"]

fruits.sort(reverse=True)
print(fruits)```

Output:

`['Cranberry', 'Banana', 'Apple']`

## 49. How Can You Randomize a Python List?

Use the `shuffle()` function from the `random` module:

```import random

x = [1,2,3,4,5]
random.shuffle(x)

print(x)```

Output (example):

`[2, 4, 5, 1, 3]`

## 50. What Does Negative Indexing Mean?

Negative indexing means indexing starts from the “other end” of a sequence.

This means the last element of a list is at the` -1` index, the second at `-2`, and so on.

For example:

```nums = [1,2,3,4,5]
print(nums[-2])```

Output:

`4`

## Conclusion

That is a lot of Python interview questions.

Thanks for reading. Happy coding, and the best of luck with an exam or interview!

I’d love to join your LinkedIn network. Feel free to connect Artturi Jalli.