Python interview questions
Prepare for your Python interview with these common questions and answers.
01What is Python? What are the benefits of using it?
Python is a high-level, interpreted, general-purpose programming language. Its design philosophy emphasizes code readability with its notable use of significant whitespace.
Benefits include:
- Easy to learn and read
- Large standard library
- Dynamically typed
- Portable across different platforms
- Supports multiple programming paradigms (procedural, object-oriented, functional)
02What is the difference between a list and a tuple?
The main difference is that lists are mutable, meaning their elements can be changed after they are created. Tuples are immutable, meaning they cannot be changed. Tuples are generally faster than lists.
03What are decorators in Python?
Decorators are a design pattern in Python that allows a user to add new functionality to an existing object (like a function) without modifying its structure. They are a form of metaprogramming and are implemented as functions that take another function as an argument and return a new function.
04What is the difference between `.py` and `.pyc` files?
.py files contain the source code of a program. .pyc files contain the bytecode of the program. .pyc files are created by the Python interpreter when a .py file is imported. They are used to speed up subsequent imports.
05What is PEP 8?
PEP 8 is the official style guide for Python code. It provides conventions for writing readable and consistent Python code. Following PEP 8 makes code easier to read and maintain for yourself and others.
06What is namespacing in Python?
A namespace is a system that has a unique name for each and every object in Python. An object might be a variable or a method. Python maintains a namespace in the form of a Python dictionary. There are Local, Global, and Built-in namespaces.
07What are Python's built-in data types?
Python has several built-in data types:
- Text Type:
str - Numeric Types:
int,float,complex - Sequence Types:
list,tuple,range - Mapping Type:
dict - Set Types:
set,frozenset - Boolean Type:
bool - Binary Types:
bytes,bytearray,memoryview
08What is a lambda function?
A lambda function is a small anonymous function. It can take any number of arguments, but can only have one expression. They are syntactically restricted to a single expression. They are often used when you need a simple function for a short period.
09What is `pass` in Python?
The pass statement is a null operation; nothing happens when it executes. It is used as a placeholder in compound statements, where the syntax requires a statement but no action is needed, like in empty function or class definitions.
10What is the difference between `range` and a list?
range() is a function that returns a sequence of numbers. It generates the numbers on demand as you iterate over it, which makes it very memory efficient. A list is a collection that stores all its elements in memory at once.
11What are generators?
Generators are a simple way of creating iterators. A generator is a function that returns an iterator object which we can iterate over (one value at a time). It is defined like a normal function but uses the yield statement instead of return.
12What are `*args` and `**kwargs`?
*args and **kwargs are used to pass a variable number of arguments to a function.
*argsis used to send a non-keyworded, variable-length argument list to the function. It will be a tuple.**kwargsallows you to pass keyworded, variable-length arguments. It will be a dictionary.
13What is the difference between a module and a package?
A module is a single Python file (.py). A package is a collection of modules in a directory. A package directory must contain a special file named __init__.py (which can be empty).
14What is the GIL (Global Interpreter Lock)?
The GIL is a mutex that protects access to Python objects, preventing multiple threads from executing Python bytecode at the same time. This means that in CPython, only one thread can execute Python code at once, even on a multi-core processor. It simplifies memory management but limits true parallelism.
15How is memory managed in Python?
Memory management in Python involves a private heap containing all Python objects and data structures. The management of this private heap is ensured by the Python memory manager. It uses a combination of reference counting and a cyclic garbage collector.
16What are list comprehensions?
List comprehensions provide a concise way to create lists. The syntax is [expression for item in iterable if condition]. They are often more readable and faster than using a for loop to build a list.
17What is the `__init__` method?
The __init__ method is a special method in Python classes. It is a constructor that is automatically called when you create a new instance of a class. It is used to initialize the attributes of an object.
18What is `self` in a class?
self represents the instance of the class. By using the self keyword, we can access the attributes and methods of the class in python. It is the first argument passed to instance methods.
19How do you handle exceptions in Python?
Exceptions are handled using a try...except block. The code that might raise an exception is placed in the try block. The code to handle the exception is placed in the except block. You can also use else (runs if no exception) and finally (always runs).
20What is the difference between `append()` and `extend()` on lists?
append() adds its argument as a single element to the end of a list. extend() iterates over its argument and adds each element to the list, extending the list.
21What is pickling and unpickling?
Pickling is the process whereby a Python object hierarchy is converted into a byte stream. Unpickling is the inverse operation. This is useful for storing Python objects in a file or database, or for transmitting them over a network.
22What are Python dictionaries?
Dictionaries are Python's implementation of a data structure more generally known as an associative array. A dictionary consists of a collection of key-value pairs. Each key-value pair maps the key to its associated value. Keys must be unique and immutable.
23How do you copy an object in Python?
You can use the copy module.
- Shallow Copy (
copy.copy()): Creates a new object but inserts references into it to the objects found in the original. - Deep Copy (
copy.deepcopy()): Creates a new object and recursively copies all objects found in the original.
24What is monkey patching?
Monkey patching refers to dynamic (or run-time) modifications of a class or module. In Python, you can change the behavior of code at runtime. For example, you can replace a method of a class with a different one.
25What does `if __name__ == '__main__':` do?
This is a common idiom in Python. The code inside this block will only run when the Python script is executed directly (not when it is imported as a module into another script). It allows a script to be both runnable and importable.
26What are virtual environments?
A virtual environment is a self-contained directory tree that contains a Python installation for a particular version of Python, plus a number of additional packages. They are used to manage dependencies for different projects, avoiding conflicts between package versions.
27How does Python's `for` loop work internally?
The for loop in Python is technically a foreach loop. It iterates over an iterable object. It calls the iter() function on the object, which returns an iterator. The loop then calls the next() method on the iterator for each cycle until a StopIteration exception is raised.
28What is duck typing?
Duck typing is a concept related to dynamic typing, where the type or the class of an object is less important than the methods it defines. The name comes from the phrase: 'If it looks like a duck, swims like a duck, and quacks like a duck, then it probably is a duck.' In Python, you don't need to check an object's type, just if it has the required methods.
29What are metaclasses?
Metaclasses are 'the stuff that creates classes'. A class is an instance of a metaclass. In Python, type is the default metaclass. You can create your own metaclasses to modify how classes are created, for example, to automatically add methods or attributes to a class.
30Explain slicing in Python.
Slicing is a feature that enables accessing parts of a sequence (like a list, tuple, or string). The syntax is [start:stop:step]. start is the index of the first element, stop is the index of the last element (not included), and step is the increment between indices.
Preparing for a role?
Tell us what you’re aiming for. A mentor can help you close the gaps before the interview.