As a senior software engineer with extensive experience in Python, JavaScript/TypeScript, Java, Go, C++, and full-stack development, I‘ve had the privilege of working with some of the top companies in the industry. Throughout my career, I‘ve noticed that Python has become one of the most sought-after programming languages, with its simplicity, powerful libraries, and versatility making it a top choice for organizations across various sectors, from tech giants like Intel, IBM, and NASA to leading streaming platforms like Netflix and Spotify.
To crack the online assessments and interviews for these companies, it‘s crucial for Python developers to have a deep understanding of the language‘s core concepts, advanced features, and common interview questions. In this comprehensive guide, I‘ll share my expertise and insights to help you prepare for your next Python interview and showcase your mastery of the language.
Fundamental Python Interview Questions
1. Is Python a Compiled or an Interpreted Language?
One of the most common questions asked in Python interviews is whether the language is compiled or interpreted. The answer is that Python is both a compiled and an interpreted language, with the compilation and interpretation processes happening at different stages of the execution.
When you write Python code and run it, the source code (.py files) is first compiled into an intermediate form called bytecode (.pyc files). This bytecode is a lower-level representation of your code that can be executed by the Python Virtual Machine (PVM), which is an interpreter.
The compilation process happens during the initial execution of the code, and the resulting bytecode is cached for subsequent runs, making the execution faster. This blurring of the line between compilation and interpretation is why Python is often considered an interpreted language in practice.
Some Python implementations, like PyPy, take this a step further by using Just-In-Time (JIT) compilation, where the Python code is compiled into machine code at runtime for even faster execution.
2. How Can You Concatenate Two Lists in Python?
Concatenating two lists in Python can be done using two main approaches:
Using the + operator:
a = [1, 2, 3] b = [4, 5, 6] res = a + b print(res) # Output: [1, 2, 3, 4, 5, 6]This method creates a new list by joining the two lists together.
Using the
extend()method:a = [1, 2, 3] b = [4, 5, 6] a.extend(b) print(a) # Output: [1, 2, 3, 4, 5, 6]This method modifies the original list
aby adding the elements ofbto it.
Both approaches are commonly used, and the choice between them depends on your specific use case and coding style preferences.
3. Difference Between for Loop and while Loop in Python
The main differences between for and while loops in Python are:
Usage:
forloops are typically used when you know the number of iterations in advance, often with iterables like lists, tuples, or ranges.whileloops are used when you don‘t know the exact number of iterations, and the loop continues as long as a certain condition is met.Syntax:
forloops have a more concise syntax, where you directly iterate over an iterable.whileloops require you to initialize a variable and update it within the loop to control the number of iterations.
Example:
# for loop
for i in range(5):
print(i)
# while loop
c = 0
while c < 5:
print(c)
c += 1Both loops will output the same result: 0 1 2 3 4.
4. How Do You Floor a Number in Python?
To floor a number in Python, you can use the math.floor() function, which returns the largest integer less than or equal to the given number.
import math
n = 3.7
floor_num = math.floor(n)
print(floor_num) # Output: 3The math.ceil() function, on the other hand, returns the smallest integer greater than or equal to the given number.
5. What is the Difference Between / and // in Python?
In Python, the / operator represents precise division, which returns a floating-point number, while the // operator represents floor division, which returns an integer.
Example:
print(5 / 2) # Output: 2.5
print(5 // 2) # Output: 2The // operator always rounds down the result to the nearest integer, even for negative numbers.
6. Is Indentation Required in Python?
Yes, indentation is required in Python. Python uses whitespace (tabs or spaces) to define code blocks, such as the body of a function, loop, or conditional statement. This makes the code more readable and enforces a consistent coding style.
Proper indentation is crucial in Python, as it is used to determine the scope and structure of the code. Incorrect indentation can lead to syntax errors and unexpected behavior in your Python programs.
7. Can We Pass a Function as an Argument in Python?
Yes, you can pass functions as arguments to other functions in Python. This is a concept known as higher-order functions, where a function can take another function as an argument, return a function, or both.
Example:
def add(x, y):
return x + y
def apply_func(func, a, b):
return func(a, b)
print(apply_func(add, 3, 5)) # Output: 8In this example, the add function is passed as an argument to the apply_func function, which then applies the add function to the given arguments 3 and 5.
8. What is a Dynamically Typed Language?
Python is a dynamically typed language, which means that the data type of a variable is determined at runtime, not at compile-time. This allows you to assign any type of value to a variable without having to declare its data type explicitly.
Example:
x = 10 # x is an integer
x = "Hello" # x is now a stringIn contrast, statically typed languages, like C or Java, require you to declare the data type of a variable, and the type cannot change during the program‘s execution.
9. What is pass in Python?
The pass statement in Python is a placeholder that does nothing. It is used when a statement is syntactically required, but no action is to be taken.
The pass statement is commonly used when defining empty functions, classes, or loops during the development process, as it keeps the code syntactically correct until you‘re ready to add the actual functionality.
Example:
def my_function():
pass # Placeholder, no functionality yet10. How Are Arguments Passed by Value or by Reference in Python?
Python‘s argument-passing model is neither "Pass by Value" nor "Pass by Reference", but rather "Pass by Object Reference".
Depending on the type of object you pass as an argument, the function will behave differently:
- For immutable objects (like integers, floats, or strings), the function behaves like "Pass by Value", as the object‘s value cannot be changed.
- For mutable objects (like lists or dictionaries), the function behaves like "Pass by Reference", as the object‘s state can be modified.
Example:
def call_by_val(x):
x = x * 2
return x
def call_by_ref(b):
b.append("D")
return b
a = ["E"]
num = 6
updated_num = call_by_val(num)
updated_list = call_by_ref(a)
print("Updated value after call_by_val:", updated_num) # Output: 12
print("Updated list after call_by_ref:", updated_list) # Output: [‘E‘, ‘D‘]Intermediate Python Interview Questions
11. What is a Lambda Function?
A lambda function, also known as an anonymous function, is a small, one-line function that can have any number of arguments but only one expression. The lambda keyword is used to define these functions.
Example:
s1 = ‘GeeksforGeeks‘
s2 = lambda func: func.upper()
print(s2(s1)) # Output: GEEKSFORGEEKSIn this example, we define a lambda function s2 that takes a function as an argument and converts the string to uppercase.
12. What is List Comprehension? Give an Example.
List comprehension is a concise way to create a new list by applying an expression to each item in an existing iterable (such as a list or range). It helps write cleaner and more readable code compared to traditional looping techniques.
Example:
a = [2, 3, 4, 5]
res = [val ** 2 for val in a]
print(res) # Output: [4, 9, 16, 25]In this example, we create a new list res by applying the square operation to each element in the list a.
13. What are *args and **kwargs?
*args (non-keyword arguments) and **kwargs (keyword arguments) are special syntax in Python that allow you to pass a variable number of arguments to a function.
*args allows you to pass an arbitrary number of non-keyword arguments to a function, which are then packed into a tuple.
def fun(*argv):
for arg in argv:
print(arg)
fun(‘Hello‘, ‘Welcome‘, ‘to‘, ‘GeeksforGeeks‘)**kwargs allows you to pass an arbitrary number of keyword arguments to a function, which are then packed into a dictionary.
def fun(**kwargs):
for key, value in kwargs.items():
print(f"{key} == {value}")
fun(s1=‘Geeks‘, s2=‘for‘, s3=‘Geeks‘)14. What is a break, continue, and pass in Python?
break: Thebreakstatement is used to terminate the loop or statement in which it is present. After thebreakstatement, the control passes to the next statement outside the loop.continue: Thecontinuestatement is the opposite of thebreakstatement. It is used to skip the current iteration of the loop and move to the next iteration.pass: Thepassstatement in Python is a placeholder that does nothing. It is used when a statement is syntactically required, but no action is to be taken.
15. What is the Difference Between a Set and Dictionary?
The main differences between a Set and a Dictionary in Python are:
Data Structure: A Set is an unordered collection of unique elements, while a Dictionary is an unordered collection of key-value pairs.
Syntax: Sets are defined using curly braces
{}or theset()function, while Dictionaries are defined using curly braces with key-value pairs separated by colons{key: value}.Uniqueness: Sets only store unique elements, while Dictionaries store unique keys, but the values can be duplicates.
Operations: Sets support operations like union, intersection, and difference, while Dictionaries are used for key-value lookups, insertions, and deletions.
16. What are the Built-in Data Types in Python?
The main built-in data types in Python are:
- Numeric: Integer, Float, Boolean, Complex
- Sequence Types: String, List, Tuple, Range
- Mapping Type: Dictionary
- Set Types: Set, Frozen Set
These data types allow you to store and manipulate different kinds of data in your Python programs.
17. What is the Difference Between a Mutable and an Immutable Data Type?
The main difference between mutable and immutable data types in Python is that mutable data types can be edited at runtime, while immutable data types cannot.
Mutable data types:
- List, Dictionary, Set
Immutable data types:
- Integer, Float, Boolean, String, Tuple
For example, you can modify the elements of a list (a mutable data type) after it has been created, but you cannot modify the individual characters of a string (an immutable data type).
18. What is a Variable Scope in Python?
Variable scope in Python refers to the location where a variable is defined and the parts of the program where it can be accessed. Python has the following variable scopes:
- Local Variables: Variables defined within a function, which can only be accessed within that function.
- Global Variables: Variables defined outside of any function, which can be accessed from anywhere in the program.
- Module-level Scope: Variables defined at the module (file) level, which can be accessed from anywhere within that module.
- Built-in Scope: Variables and functions that are part of the Python standard library, which can be accessed from anywhere in the program.
Understanding variable scope is crucial for avoiding naming conflicts and ensuring that your variables are accessible when needed.
19. How is a Dictionary Different from a List?
The main differences between a Dictionary and a List in Python are:
- Data Structure: A List is an ordered collection of items, while a Dictionary is an unordered collection of key-value pairs.
- Access: Lists are accessed by index, while Dictionaries are accessed by unique keys.
- Uniqueness: Lists can contain duplicate elements, while Dictionary keys must be unique.
- Use Cases: Lists are better suited for sequential data, while Dictionaries are better for associative data (key-value pairs).
For example, a list can store [10, 20, 30], while a dictionary can store {"a": 10, "b": 20, "c": 30}.
20. What is Docstring in Python?
Python documentation strings (or docstrings) provide a convenient way to associate documentation with Python modules, functions, classes, and methods. Docstrings are declared using triple single quotes ‘‘‘ or triple double quotes """ just below the class, method, or function declaration.
Docstrings can be accessed using the __doc__ attribute of the object or by using the help() function.
Example:
def my_function(a, b):
‘‘‘
Adds two numbers and returns the result.
Args:
a (int): The first number to be added.
b (int): The second number to be added.
Returns:
int: The sum of the two numbers.
‘‘‘
return a + bDocstrings help document your code and make it more readable and maintainable for other developers.
21. How is Exception Handling Done in Python?
Python uses the try, except, and finally keywords to handle exceptions. The try block contains the code that might raise an exception, the except block handles the exception, and the finally block is executed regardless of whether an exception occurred or not (often used for cleanup tasks).
Example:
n = 10
try:
res = n / 0 # This will raise a ZeroDivisionError
except ZeroDivisionError:
print("Can‘t be divided by zero!")