Python Mock Interview Questions
Top 40+ Python Interview Questions and Answers (Latest 2024)
1. What is Python? List some popular applications of Python in the world of technology.
Python is a widely-used general-purpose, high-level programming language. It was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with an emphasis on code readability, and its syntax allows programmers to express their concepts in fewer lines of code.
It is used for:
- System Scripting
- Web Development
- Game Development
- Software Development
- Complex Mathematics
2. Is Python a compiled language or an interpreted language?
Actually, Python is a partially compiled language and partially interpreted language. The compilation part is done first when we execute our code and this will generate byte code internally this byte code gets converted by the Python virtual machine(p.v.m) according to the underlying platform(machine+operating system).
3.What does the ‘#’ symbol do in Python?
‘#’ is used to comment on everything that comes after on the line.
4. What is the difference between a Mutable datatype and an Immutable data type?
Mutable data types can be edited i.e., they can change at runtime. Eg – List, Dictionary, etc.
Immutable data types can not be edited i.e., they can not change at runtime. Eg – String, Tuple, etc.
5. What is the difference between a Set and Dictionary?
The set is unordered collection of unique items that is iterable and mutable. A dictionary in Python is an ordered collection of data values, used to store data values like a map.
6. What is List Comprehension? Give an Example.
List comprehension is a syntax construction to ease the creation of a list based on existing iterable.
For Example:
my_list = [i for i in range(1, 10)]
7. What is a pass in Python?
Pass means performing no operation or in other words, it is a placeholder in the compound statement, where there should be a blank left and nothing has to be written there.
8. What is the difference between / and // in Python?
/ represents precise division (result is a floating point number) whereas // represents floor division (result is an integer). For Example:
print(5//2) # 2
print(5/2) # 2.5
9. What is a break, continue, and pass in Python?
- The break statement is used to terminate the loop or statement in which it is present. After that, the control will pass to the statements that are present after the break statement, if available.
- Continue is also a loop control statement just like the break statement. continue statement is opposite to that of the break statement, instead of terminating the loop, it forces to execute the next iteration of the loop.
- Pass means performing no operation or in other words, it is a placeholder in the compound statement, where there should be a blank left and nothing has to be written there.
10. What are the common built-in data types in Python?
There are several built-in data types in Python. Python provides type() and isinstance() functions to check the type of these variables. These data types can be grouped into the following categories-
- None Type:
None keyword represents the null values in Python. Boolean equality operation can be performed using these NoneType objects.
Class Name | Description |
---|---|
NoneType | Represents the NULL values in Python. |
- Numeric Types:
There are three distinct numeric types – integers, floating-point numbers, and complex numbers. Additionally, booleans are a sub-type of integers.
Class Name | Description |
---|---|
int | Stores integer literals including hex, octal and binary numbers as integers |
float | Stores literals containing decimal values and/or exponent signs as floating-point numbers |
complex | Stores complex numbers in the form (A + Bj) and has attributes: real and imag |
bool | Stores boolean value (True or False). |
- Sequence Types:
According to Python Docs, there are three basic Sequence Types – lists, tuples, and range objects. Sequence types have the in and not in operators defined for their traversing their elements. These operators share the same priority as the comparison operations.
Class Name | Description |
---|---|
list | Mutable sequence used to store collection of items. |
tuple | Immutable sequence used to store collection of items. |
range | Represents an immutable sequence of numbers generated during execution. |
str | Immutable sequence of Unicode code points to store textual data. |
- Mapping Types:
A mapping object can map hashable values to random objects in Python. Mappings objects are mutable and there is currently only one standard mapping type, the dictionary.
Class Name | Description |
---|---|
dict | Stores comma-separated list of key: value pairs |
- Set Types:
Currently, Python has two built-in set types – set and frozenset. set type is mutable and supports methods like add() and remove(). frozenset type is immutable and can’t be modified after creation.
Class Name | Description |
---|---|
set | Mutable unordered collection of distinct hashable objects. |
frozenset | Immutable collection of distinct hashable objects. |
11. What are lists and tuples? What is the key difference between the two?
Feature | List | Tuple |
---|---|---|
Syntax | [] | () |
Mutability | Mutable | Immutable |
Methods | Many (e.g., append, remove) | Few (e.g., count, index) |
Performance | Slower (due to mutability) | Faster (due to immutability) |
Memory Usage | Higher | Lower |
Example | list=[2,3,4,51,77] | t1=(3,7,6,8,4) |
12. What is the difference between global and local scope?
- A variable created inside a function belongs to the local scope of that function, and can only be used inside that function.
- A variable created in the main body of the Python code is a global variable and belongs to the global scope. Global variables are available from within any scope, global and local.
13. How can you convert a string to an integer?
- You can use the int() function, like this:
num = "5"
convert = int(num)
14. Which collection does not allow duplicate members?
- SET
15. What are Membership Operators?
In Python, the in
and not in
operators are used to check for membership (whether a value exists) in a collection such as a list, tuple, string, set, or dictionary.
my_list = [1, 2, 3, 4, 5]
print(3 in my_list) # True
print(6 in my_list) # False
my_string = "Hello, World!"
print('H' in my_string) # True
print('h' in my_string) # False (case-sensitive)
16. Which statement can be used to avoid errors if an if statement has no content?
- The pass statement
for i in range(5):
pass # Do nothing for each iteration
17. What is the difference between ==
and is
in Python?
- Answer:
==
is used to compare the values of two objects.is
is used to compare the identities of two objects, i.e., whether they refer to the same object in memory.
a = [1, 2, 3]
b = [1, 2, 3]
print(a == b) # True, because the values are the same
print(a is b) # False, because they are different objects in memory
18. What is a lambda function in Python?
- A lambda function is a small anonymous function defined with the
lambda
keyword. It can take any number of arguments, but only one expression.
add = lambda x, y: x + y
print(add(2, 3)) # Output: 5
19. How do you create a dictionary in Python?
- A dictionary in Python is created using curly braces
{}
and key-value pairs separated by a colon:
.
Example:
my_dict = {'name': 'Alice', 'age': 25, 'city': 'New York'}
print(my_dict)
20.What is the difference between append()
and extend()
in Python lists?
append()
: Adds a single element to the end of the list.extend()
: Adds all elements of an iterable (like a list or set) to the end of the list.
my_list = [1, 2, 3]
my_list.append([4, 5]) # List inside the list
print(my_list) # Output: [1, 2, 3, [4, 5]]
my_list = [1, 2, 3]
my_list.extend([4, 5]) # Adds each element to the list
print(my_list) # Output: [1, 2, 3, 4, 5]
t)
21. How do you handle exceptions in Python?
- You can handle exceptions in Python using
try
,except
,else
, andfinally
blocks.
Example:
try:
x = 10 / 0
except ZeroDivisionError:
print("You can't divide by zero!")
else:
print("Division was successful.")
finally:
print("This will always execute.")
22. How do you merge two dictionaries in Python?
- You can merge dictionaries using the
update()
method or the**
unpacking operator.
Example:
dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
# Using update()
dict1.update(dict2)
print(dict1) # Output: {'a': 1, 'b': 3, 'c': 4}
# Using unpacking (Python 3.5+)
merged_dict = {**dict1, **dict2}
print(merged_dict) # Output: {'a': 1, 'b': 3, 'c': 4}
23. How do you define a function in Python?
A function is defined using the def
keyword followed by the function name and parameters.
Example:
def radha(name):
print(f"Hello, {name}!")
24.How can you reverse a list in Python?
Use the reverse()
method or slicing.
Example:
my_list = [1, 2, 3]
my_list.reverse() # In-place reversal
print(my_list) # Output: [3, 2, 1]
reversed_list = my_list[::-1]
25. What is the difference between del
, remove()
, and pop()
in Python lists?
del
: Deletes a variable or an item by index.remove()
: Removes the first occurrence of a value.pop()
: Removes and returns an item by index.
26. How do you convert a string to a list in Python?
Use the split()
method to convert a string into a list.
Example:
my_string = "Hello World"
my_list = my_string.split()
print(my_list) # Output: ['Hello', 'World']
27. What does the global
keyword do in Python?
The global
keyword allows a variable to be modified outside the scope of the current function, referencing the global variable.
28. What is the difference between deepcopy()
and copy()
in Python?
copy()
creates a shallow copy, meaning nested objects are still referenced.deepcopy()
creates a deep copy, meaning nested objects are also copied.
29. How do you create a set in Python?
A set is created using curly braces {}
or the set()
function.
Example:
my_set = {1, 2, 3}
print(my_set)
30. How do you remove duplicates from a list?
Convert the list to a set and then back to a list.
Example:
my_list = [1, 2, 3, 3, 4]
unique_list = list(set(my_list)) # convert into set using set fn
31. What is the use of enumerate()
in Python?
enumerate()
is used to get both the index and the value when looping over a sequence.
Example:
for index, value in enumerate(['a', 'b', 'c']):
print(index, value)
0 1
1 b
3 c
32. What does the isinstance()
function do?
It checks if an object is an instance or subclass of a specified class.
33. How do you create a class in Python?
A class is defined using the class
keyword.
Example:
class Dog:
def __init__(self, name):
self.name = name
34. What is the __init__()
method in Python?
__init__()
is a special method used to initialize a newly created object of a class.
35. What is the difference between break
and continue
?
break
: Exits the current loop.continue
: Skips the rest of the current loop iteration and goes to the next iteration.
36. How do you import a module in Python?
Use the import
keyword.
Example:
import math
print(math.sqrt(16)) # Output: 4.0