Skip to content

Common Interview Questions

Easy

What is Python?

Python is a high-level, interpreted programming language known for its simplicity and readability. It supports multiple programming paradigms, including procedural, object-oriented, and functional programming. Python is widely used in web development, data analysis, artificial intelligence, scientific computing, and more.

What are Python’s key features?

Python is interpreted, dynamically typed, and garbage-collected. It has a simple syntax that emphasizes readability, supports multiple programming paradigms, and has a vast standard library. Python also has strong community support and is highly extensible with third-party libraries.

What are Python’s data types?

Python has several built-in data types, including numeric types (int, float, complex), sequences (list, tuple, range), text type (str), set types (set, frozenset), and mappings (dict). Additionally, it includes types like bool and NoneType.

What is a Python list?

A list is a mutable, ordered collection of items in Python. It can store items of different data types and is defined using square brackets, e.g., my_list = [1, 2, "three"]. Lists support various operations, such as slicing, appending, and removing elements.

What is the difference between a list and a tuple?

Lists are mutable, meaning their elements can be modified, while tuples are immutable. Tuples are defined using parentheses () instead of square brackets []. Tuples are generally faster than lists and are used for data that shouldn’t change.

How is memory managed in Python?

Python uses automatic memory management, including garbage collection. It tracks object references and deallocates memory for objects no longer in use. The memory management process also relies on reference counting and the cyclic garbage collector. More on this found here.

What is the difference between is and == in Python?

The is operator checks for object identity (whether two variables reference the same object), while == checks for value equality (whether the values of two variables are equal). For example, a = [1, 2] and b = [1, 2]; a == b is True, but a is b is False.

What are Python’s control flow statements?

Python has standard control flow statements like if, elif, and else for conditional execution, and loops like for and while. The break, continue, and pass statements provide finer control over loop execution.

What are Python’s keywords?

Keywords are reserved words in Python that cannot be used as identifiers. Examples include def, return, if, else, elif, try, except, class, from, import, and with.

What are Python functions, and how are they defined?

Functions in Python are reusable blocks of code defined using the def keyword. For example:

def greet(name):
return f"Hello, {name}"

Mid

What is the difference between shallow and deep copies in Python?

A shallow copy creates a new object but inserts references to the original objects. A deep copy creates a new object and recursively copies all objects within it. The copy module provides copy() for shallow copies and deepcopy() for deep copies.

How does Python handle exceptions?

Python handles exceptions using try, except, else, and finally blocks. For example:

try:
x = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
else:
print("Will execute if no exception!")
finally:
print("Execution complete")

What are Python decorators?

Decorators are functions that modify the behavior of other functions or methods. They are applied using the @decorator syntax. For example:

def decorator(func):
def wrapper():
print("Before")
func()
print("After")
return wrapper

What is Python’s Global Interpreter Lock (GIL)?

The GIL is a mutex that prevents multiple threads from executing Python bytecode simultaneously. It simplifies memory management but can limit the performance of CPU-bound multi-threaded programs. More about the GIL here.

What is the difference between @staticmethod and @classmethod?

@staticmethod defines a method that doesn’t operate on an instance or class. Think of it as just a function that is attached to a class namespace.

@classmethod operates on the class and takes cls as its first argument instead of self.

How does Python’s with statement work?

The with statement is used for resource management. It ensures resources like files are properly released. For example: Using the with statement means utilizing Pythons context-managers. More on those here.

with open('file.txt', 'r') as file:
content = file.read()

What is Python’s __init__ method?

The __init__ method is the constructor in Python. It is automatically invoked after an object is created and is used to initialize object attributes. This method does not create the object but rather prepares it for work.

What are Python’s lambda functions?

Lambda functions are anonymous, single-expression functions created using the lambda keyword. For example: Most often used where we need a function and can express it in a single line

add = lambda x, y: x + y
sorting = sorted(some_list_of_dict, key=lambda x: x["number"])

What are Python modules and packages?

A module is a file containing Python code, while a package is a directory containing multiple modules and an __init__.py file. They allow code reuse and organization.

Senior

How does Python handle memory leaks?

Memory leaks in Python can occur due to circular references or improper resource management. The garbage collector can clean up circular references, but careful coding practices (like using weak references) help avoid such leaks.

What is metaprogramming in Python?

Metaprogramming involves writing programs that manipulate other programs or themselves. In Python, metaprogramming can be achieved using metaclasses, decorators, and the inspect module.

What are Python’s metaclasses?

Metaclasses are classes of classes. They define the behavior and properties of class objects. Custom metaclasses can be created by inheriting from type.

How do you optimize Python code?

Optimization techniques include using built-in functions, list comprehensions, generators, and libraries like NumPy. Profiling tools like cProfile can identify bottlenecks.

What are Python’s coroutines?

Coroutines are special generators that allow asynchronous programming. They are created using the async and await keywords. For example:

async def fetch_data():
await some_async_function()

How does Python’s garbage collector work?

Python’s garbage collector uses reference counting and a cyclic garbage collector for circular references. The gc module provides tools to interact with garbage collection.

What is the difference between __getattr__ and __getattribute__?

__getattr__ is called only when an attribute is not found in the usual way, while __getattribute__ is called for every attribute access.

How are Python objects serialized?

Python objects can be serialized using the pickle module. JSON can also be used for serialization, especially for simpler data structures.

How does Python manage multithreading?

Python’s threading module provides multithreading support, but the GIL limits performance for CPU-bound tasks. Use the multiprocessing module for CPU-intensive tasks.

What are Python’s asynchronous libraries?

Python supports asynchronous programming through libraries like asyncio, aiohttp, and Trio. These libraries allow efficient I/O-bound concurrency.