Python language created by Guido van Rossum in 1991. This is one of the most commonly used programming languages and it used in Machine Learning, Artificial Intelligence, Web Development, and more. The growing demand for Python developers, our Python interview questions walkthrough will help you in job interviews.
Many top companies like IBM, NASA, Facebook, and Netflix prefer Python for its powerful libraries and clean syntax. To crack their interview rounds, candidates need to be well-prepared with the right Python interview questions.
We will cover three major level of interview questions:
- Beginner Python Interview Questions
- Intermediate Python Interview Questions
- Advanced Python Interview Questions
1. What is Python and why is it used?
Python is a high-level programming language. It designed with a focus on code readability, using significant indentation to enhance clarity. It features dynamic typing and automatic memory management through garbage collection. Python supports various programming styles, including structured, object-oriented, and functional programming approaches. It is mostly used in data science, web applications, software development, and machine learning. Python is flexible and can run on many different platforms.
2. Is Python interpreted language?
Yes, Python is an interpreted language. This means that Python code is executed line-by-line by the Python interpreter rather than being compiled into machine code. The Python interpreter reads the source code, translates it into an intermediate form called bytecode, and then executes it, making Python highly flexible and allowing for quick testing and debugging during development.
3. Tell us the key differences of Tuple vs List?
When comparing Tuple vs List in Python, both are used to store collections of items, but they serve different purposes:
- Mutability:
- Syntax:
- List: Defined using square brackets []. Example: my_list = [1, 2, 3]
- Tuple: Defined using parentheses (). Example: my_tuple = (1, 2, 3)
- Performance:
- List: Due to their mutability, lists are slower and consume more memory.
- Tuple: Tuples are faster and more memory-efficient, making them ideal for fixed data.
- Use Cases:
- List: Best for scenarios where data may change, like dynamic data storage.
- Tuple: Suitable for data that remains constant, such as configurations or coordinates.
4. What is Python docstring?
A Python docstring is a special string used to document modules, classes, functions, and methods in Python. It provides a convenient way to include descriptive information about the purpose and behavior of the code. A Python docstring is written as the first statement in a function, class, or module, enclosed in triple quotes (""" """ or ''' '''). These docstrings can be accessed using the __doc__ attribute or built-in help functions.
Example of a Python docstring:
1def greet(name):
2 """
3 This function takes a name as input and returns a greeting message.
4
5 Parameters:
6 name (str): The name of the person to greet
7
8 Returns:
9 str: Greeting message
10 """
11 return f"Hello, {name}!"
5. Do you know the difference Between remove() Function and del Statement?
- remove() Function:
- Purpose: The remove() function is used to remove the first occurrence of a specified value from a list.
- Usage: It works only with lists and requires the value to be present in the list; otherwise, it raises a ValueError.
- Syntax: list.remove(value)
- Example:
1my_list = [1, 2, 3, 4]
2my_list.remove(3) # Removes the value 3 from the list
3print(my_list) # Output: [1, 2, 4]
del Statement:
- Purpose: The del statement can be used to delete elements by index, entire variables, slices of lists, or even objects.
- Usage: More versatile than remove(), del can remove items by index in a list, delete variables, or entire objects.
- Syntax: del list[index] or del variable
- Example
1my_list = [1, 2, 3, 4]
2del my_list[2] # Removes the element at index 2 (value 3)
3print(my_list) # Output: [1, 2, 4]
4
5x = 10
6del x # Deletes the variable x
6. What is pickling and unpickling in Python?
Pickling and Unpickling in Python are processes used to serialize and deserialize objects, respectively.
- Pickling:
- Definition: Pickling is the process of converting a Python object (like a list, dictionary, or class instance) into a byte stream, which can then be stored in a file or transferred over a network.
- Purpose: This allows objects to be saved and reused later, even after the program has ended.
- How to Use: You can use the pickle module in Python to serialize objects.
- Example:
1import pickle
2my_dict = {'name': 'Alice', 'age': 25}
3with open('data.pkl', 'wb') as file:
4 pickle.dump(my_dict, file) # Pickling the object
- Unpickling:
- Definition: Unpickling is the reverse process of converting the byte stream back into the original Python object.
- Purpose: It restores the saved object to its original state, allowing the program to use it again.
- How to Use: The pickle module can also be used to deserialize objects.
- Example:
1import pickle
2with open('data.pkl', 'rb') as file:
3 my_dict = pickle.load(file) # Unpickling the object
4print(my_dict) # Output: {'name': 'Alice', 'age': 25}
7. What are decorators in Python?
In Python, decorators are a powerful and flexible feature that allows you to modify the behavior of functions or methods without changing their actual code. A decorator in Python is a higher-order function that takes another function as an argument, adds some functionality to it, and returns a new function with the added behavior.
- Key Uses:
- Enhancing functionality: Decorators are often used to modify or enhance functions, such as adding logging, authentication, or validation before or after the function runs.
- Code reusability: They allow you to write reusable code that can be applied to multiple functions, reducing redundancy.
- Syntax: Decorators are defined with the @decorator_name syntax above the function you want to modify.
Example:
1def my_decorator(func):
2 def wrapper():
3 print("Before the function call")
4 func()
5 print("After the function call")
6 return wrapper
7
8@my_decorator
9def say_hello():
10 print("Hello!")
11
12say_hello()
In this example, the decorator my_decorator modifies the say_hello function by adding behavior before and after the function call.
8. What is slicing in Python?
Slicing in Python refers to the technique of extracting a portion (or subset) of a sequence, such as a list, string, or tuple, by specifying a range of indices. It allows you to access and manipulate specific parts of a sequence without modifying the original object.
Syntax for Slicing:
1sequence[start:stop:step]
- start: The starting index (inclusive).
- stop: The ending index (exclusive).
- step: The interval at which elements are selected (optional).
Example:
1my_list = [1, 2, 3, 4, 5, 6]
2subset = my_list[1:5] # Slicing from index 1 to 4
3print(subset) # Output: [2, 3, 4, 5]
In this example, the slice [1:5] extracts elements from index 1 to 4. The element at index 5 is excluded.
9. What is a Namespace in Python?
A namespace in Python is a system that manages the names of variables and objects to avoid conflicts and ensure that each name is unique. It acts like a container where names (identifiers) are mapped to objects (such as variables, functions, classes, etc.).
Python has different types of namespaces:
- Built-in Namespace: Contains names of built-in functions and exceptions like print(), len(), int(), etc.
- Global Namespace: Names defined at the global level can be accessed anywhere in the module.
- Local Namespace: Names defined inside functions are limited to the function's scope.
- Enclosing Namespace: Refers to the namespace of an enclosing function in case of nested functions.
- Example:
1x = 10 # Global namespace
2
3def my_function():
4 y = 5 # Local namespace
5 print(x + y)
6
7my_function() # Output: 15
In this example, x belongs to the global namespace, and y belongs to the local namespace of the my_function().
10. What is a lambda function in Python?
A lambda function in Python is a small, anonymous function defined using the lambda keyword. Unlike regular functions created with def, lambda functions are typically used for short, simple operations and can have any number of arguments, but only one expression. Lambda functions are often used when you need a function for a short period and don't want to define it using the traditional def keyword.
Syntax:
1lambda arguments: expression
Example:
1# Lambda function to add two numbers
2add = lambda x, y: x + y
3print(add(5, 3)) # Output: 8
In this example, the lambda function takes two arguments (x and y) and returns their sum.
11. What are Iterators in Python?
An iterator in Python is an object that allows you to traverse through all the elements in a collection (such as lists, tuples, or dictionaries) one at a time. Iterators are part of Python’s iterator protocol, which consists of the methods __iter__() and __next__().
- __iter__(): This method returns the iterator object itself and is called once at the start of the iteration.
- __next__(): This method returns the next value from the iterator. When no more data is available, it raises a StopIteration exception.
Example:
1my_list = [1, 2, 3]
2iterator = iter(my_list) # Create an iterator object
3print(next(iterator)) # Output: 1
4print(next(iterator)) # Output: 2
5print(next(iterator)) # Output: 3
In the example, the iter() function is used to create an iterator for my_list, and next() is used to retrieve the elements one by one.
Why use iterators?
- Efficiency: Iterators are memory-efficient because they return items one at a time rather than loading all elements into memory at once.
- Lazy Evaluation: Iterators calculate values on demand, making them suitable for large datasets or streams of data.
12. What is a dynamically typed language?
A dynamically typed language is a programming language where the type of a variable is determined at runtime, rather than at compile time. In such languages, you don’t need to explicitly declare the data type of a variable when writing code. Instead, the type is automatically assigned based on the value assigned to the variable during execution.
Python is a prime example of a dynamically typed language, which means that you can assign any type of data (integer, string, list, etc.) to a variable without declaring its type in advance, and the type can change during program execution.
Example in Python:
1x = 10 # x is an integer
2x = "Hello" # x is now a string
In the above example, the variable x changes its type from integer to string without any explicit type declaration.
Advantages of Dynamic Typing:
- Flexibility: Allows for easier coding as you don't have to declare variable types.
- Less code: Reduces the need for type declarations and typecasting.
Disadvantages:
- Runtime errors: Type-related errors are discovered only during execution, not during compilation.
- Performance: Dynamically typed languages can be slower than statically typed languages due to type checks at runtime.
13. What is Pass in Python?
The pass statement in Python is a placeholder statement that does nothing. It is used when a statement is syntactically required but no action is needed. Essentially, the pass statement is used to create a block of code that will be implemented later or to handle conditions where you don’t want the program to execute anything.
Key Uses:
- As a placeholder for future code.
- To define empty functions, classes, loops, or conditionals that you plan to implement later without causing a syntax error.
Example of Pass in Python:
1def my_function():
2 pass # Placeholder for future code
3
4for i in range(5):
5 pass # Loop will execute without any action
In this example, the pass statement is used inside a function and a loop, allowing the program to run without errors while the actual logic is yet to be defined.
14. What is PEP 8?
PEP 8 is the official style guide for writing clean and readable Python code. It stands for Python Enhancement Proposal 8 and provides a set of recommendations on how to format Python code to improve its readability and consistency across different projects. PEP 8 is widely followed by Python developers to maintain a uniform coding style, making it easier to collaborate and review code.
Key Guidelines of PEP 8:
- Indentation: Use 4 spaces per indentation level.
- Maximum Line Length: Limit all lines to a maximum of 79 characters.
- Blank Lines: Use blank lines to separate functions and classes.
- Naming Conventions: Follow specific naming rules:
- Variables and functions: lowercase with underscores (my_function)
- Class names: CapitalizedWords (MyClass)
- Constants: UPPERCASE_WITH_UNDERSCORES (MY_CONSTANT)
- Imports: Group imports at the top of the file, typically in this order:
- Standard library imports
- Related third-party imports
- Local application-specific imports
- Whitespace: Avoid extraneous whitespace in expressions and statements (e.g., x = 5 instead of x= 5).
15. What are Python literals?
In Python, literals are fixed values assigned directly to variables or constants in the code. They represent the data itself, such as numbers, strings, or boolean values, that do not change during program execution. Python supports several types of literals:
Types of Python Literals:
- String Literals:
- Represent text enclosed in single, double, or triple quotes.
- Numeric Literals:
- Represent numbers (integers, floating-point numbers, or complex numbers).
- Boolean Literals:
- Represent the values True and False.
- Special Literal (None):
- Represents the absence of a value or a null value using None.
- Literal Collections:
- Python provides several ways to store multiple values in literal form, such as:
- List Literals: [1, 2, 3]
- Tuple Literals: (1, 2, 3)
- Dictionary Literals: {'key1': 'value1', 'key2': 'value2'}
- Set Literals: {1, 2, 3}
- Python provides several ways to store multiple values in literal form, such as:
16. Tell us about memory management in Python?
Memory management in Python is handled automatically by Python's built-in memory manager. It allocates and deallocates memory for Python objects and data structures efficiently. Here’s how it works:
Key points of Python memory management:
- Memory Allocation:
- Python Objects: When variables or objects are created, memory is dynamically allocated by Python. This allocation is managed through Python's private heap space.
- Object Lifecycle: Each Python object has its own memory space, and Python ensures efficient memory usage through automatic allocation and deallocation.
- Garbage Collection:
- Python has a built-in garbage collector that automatically recycles memory by removing objects that are no longer in use.
- It primarily uses reference counting, where each object has a counter that tracks how many references point to it. When the reference count drops to zero, the object is deallocated.
- For dealing with circular references, Python uses an additional cyclic garbage collector.
- Dynamic Typing and Memory:
- Python’s dynamic typing means that memory is allocated when an object is created, and reallocated if the object type changes during program execution.
- Memory Pooling:
- Python uses a technique called memory pooling to manage memory more efficiently. This involves maintaining a pool of memory blocks for frequently used objects, reducing overhead for memory allocation.
- PyMalloc:
- Python's memory manager includes a custom allocator called PyMalloc for managing small objects and reducing fragmentation in memory allocation.
- Manual Memory Management:
- While Python automatically handles memory management, developers can also influence garbage collection behavior using the gc module, which allows you to manually invoke garbage collection or control thresholds.
17. What is the difference between deep copy and shallow copy in Python?
In Python, deep copy and shallow copy are two different ways of copying objects. They behave differently based on how they handle nested objects or references to other objects within a data structure.
Shallow copy
- Definition: A shallow copy creates a new object but only copies the references of the objects inside the original container. In other words, the outer object is copied, but the nested objects (like lists within lists) are still referenced.
- Effect: Changes made to the nested objects in the copied version will affect the original version, as they still share references to the same objects.
- How to Create: You can create a shallow copy using the copy() method or the copy module.
Example of Shallow Copy:
1import copy
2
3original = [[1, 2], [3, 4]]
4shallow_copy = copy.copy(original)
5
6shallow_copy[0][0] = 99 # This change will reflect in both copies
7
8print(original) # Output: [[99, 2], [3, 4]]
9print(shallow_copy) # Output: [[99, 2], [3, 4]]
Deep copy
- Definition: A deep copy creates a new object and recursively copies all the objects within the original container. This means the entire object, including all nested objects, is duplicated.
- Effect: Changes made to the deep copied object do not affect the original, as they are completely independent.
- How to Create: You can create a deep copy using the deepcopy() method from the copy module.
Example of Deep Copy:
1import copy
2
3original = [[1, 2], [3, 4]]
4deep_copy = copy.deepcopy(original)
5
6deep_copy[0][0] = 99 # This change will NOT reflect in the original
7
8print(original) # Output: [[1, 2], [3, 4]]
9print(deep_copy) # Output: [[99, 2], [3, 4]]
18. What are Python modules?
A module in Python is a file containing Python code that can define functions, classes, and variables, as well as include runnable code. Modules help organize Python code into separate files for better structure and reusability. By dividing a large program into smaller, more manageable pieces, developers can reuse code across different programs.
Key features of Python modules:
- Code Reusability: Modules allow code to be used across multiple programs, reducing duplication.
- Organization: They help organize related code into separate files, making large programs easier to manage and understand.
- Namespace Management: Modules provide a separate namespace, avoiding conflicts between functions or variables in different parts of a program.
Types of Python modules:
- Built-in Modules: Python comes with a large set of built-in modules like math, os, random, etc., which provide functions for common tasks.
- User-Defined Modules: You can create your own Python modules by saving a .py file and importing it into other scripts.
Importing modules in Python:
To use a module, you need to import it using the import statement.
Example:
1# Importing a built-in module
2import math
3
4# Using a function from the math module
5result = math.sqrt(16)
6print(result) # Output: 4.0
19. Difference Between range() and xrange() functions in Python
In Python, both range() and xrange() functions are used to generate sequences of numbers. However, they differ in how they store and handle these sequences, which impacts their performance and memory usage.
range() Function:
- Definition: In both Python 2 and Python 3, the range() function generates a list of numbers.
- Behavior: It returns a list of numbers that are generated at once, which means it stores the entire sequence in memory.
- Usage: Ideal when you need to generate and work with a sequence of numbers in Python 3.
- Example:
1numbers = range(5) # Generates [0, 1, 2, 3, 4]
2print(list(numbers)) # Output: [0, 1, 2, 3, 4]
xrange() Function (Python 2 Only):
- Definition: The xrange() function exists only in Python 2 and returns an iterator instead of a list.
- Behavior: It generates the numbers on demand (lazily), meaning it does not store the sequence in memory, but computes each number when needed.
- Usage: More memory-efficient compared to range() in Python 2, especially for large ranges.
- Example:
1numbers = xrange(5) # Creates an xrange object (not a list)
2for num in numbers:
3 print(num) # Output: 0, 1, 2, 3, 4
20. How will you check if all the characters in a string are alphanumeric?
To check if all the characters in a string are alphanumeric (i.e., either a letter or a number) in Python, you can use the isalnum() method. This built-in method returns True if all the characters in the string are alphanumeric, and False if there are any non-alphanumeric characters (like spaces, punctuation, or symbols).
Example:
1my_string = "Hello123"
2
3if my_string.isalnum():
4 print("All characters are alphanumeric.")
5else:
6 print("Not all characters are alphanumeric.")
In this example, my_string.isalnum() checks if every character in "Hello123" is either a letter or a number. The method will return True because there are no spaces or special characters.
Intermediate Python interview questions
21. What are Python Packages?
In Python, a package is a way of organizing related modules into a directory hierarchy. A package is essentially a collection of Python modules grouped together to provide a set of functionalities or features, helping to manage large codebases by breaking them down into smaller, reusable components.
Key features of Python packages:
- Modular Organization: Packages allow code to be organized into multiple modules, promoting code reuse and maintainability.
- Directories and __init__.py: A package is typically a directory that contains a special __init__.py file. This file can be empty or contain initialization code for the package.
- Nested Packages: Python packages can contain sub-packages, creating a nested structure of modules and packages.
22. Difference Between .py and .pyc Files in Python
In Python, .py and .pyc files serve different purposes and are used at different stages of the execution process.
.py Files:
- Definition: A .py file is a plain text file containing the Python source code written by the developer. These files can be executed directly by the Python interpreter.
- Usage: .py files are used to write and store Python code, including functions, classes, and logic.
- Example
1# example.py
2print("Hello, World!")
- Execution: When you run a .py file, Python compiles it to bytecode before execution.
.pyc Files:
- Definition: A .pyc file is a compiled bytecode version of a .py file. Python generates .pyc files automatically to speed up the execution of the program.
- Usage: .pyc files are not meant to be edited manually. They are generated when a .py file is executed, allowing the Python interpreter to skip the compilation step when the program runs again.
- Location: .pyc files are stored in the __pycache__ directory by default.
- Example: A compiled bytecode version of example.py would be stored as something like example.cpython-39.pyc (for Python 3.9).
23. What are Python comprehensions?
Python comprehensions are a concise way to create collections, such as lists, sets, and dictionaries, from existing iterables like lists, tuples, or strings. They allow you to write more compact and readable code by combining loops and conditional logic into a single line. The most common type is the list comprehension in Python, but there are also set, dictionary, and generator comprehensions.
24. What are Python keywords?
Python keywords are reserved words in the Python programming language that have predefined meanings and cannot be used as variable names, function names, or identifiers. These keywords are part of the language syntax and serve specific purposes, such as defining control flow, data types, and program structure.
List of Python keywords:
As of Python 3.x, some common Python keywords include:
- Control Flow Keywords: Used for decision-making, loops, and exception handling.
- if, else, elif: Conditional statements.
- for, while: Looping statements.
- try, except, finally, raise: Exception handling.
- Logical and Comparison Keywords: Used for comparisons and logical operations.
- and, or, not: Logical operators.
- is, in: Comparison operators.
- Function and Class Definition Keywords: Used for defining functions, classes, and more.
- def: Defines a function.
- class: Defines a class.
- return: Returns a value from a function.
- lambda: Creates anonymous functions.
- Variable and Value Keywords: Used for defining and managing values and memory.
- True, False: Boolean values.
- None: Represents the absence of a value.
- global, nonlocal: Declare variable scopes.
- Miscellaneous Keywords:
- with: Used for managing context (e.g., file handling).
- import, from, as: Importing modules.
- yield: Used in generator functions to return values lazily.
- pass: Placeholder for empty blocks of code.
- assert: Used for debugging purposes to check conditions.
How to check all Python keywords:
You can use the keyword module to view all the keywords available in your Python version.
1import keyword
2print(keyword.kwlist)
25. What is PYTHONPATH?
PYTHONPATH is an environment variable in Python that specifies the directories where the Python interpreter should look for modules and packages during execution. When you import a module, Python searches in the directories listed in PYTHONPATH before checking its default paths, such as the standard library or the location where Python is installed.
Purpose of PYTHONPATH:
- Custom Module Search Path: You can use PYTHONPATH to add directories where you store your custom Python modules and packages, ensuring Python can locate them during imports.
- Flexibility: By setting PYTHONPATH, you can control the search paths for Python modules without changing the default environment or project structure.
26. What are the advantages of Python?
There are some of advantages of Python are as follow:
- Easy to Learn: Simple syntax and readability make Python beginner-friendly.
- Cross-Platform: Works on Windows, macOS, and Linux without modification.
- Extensive Libraries: Offers powerful libraries for web development, data science, AI, and more (e.g., Django, Pandas, TensorFlow).
- Interpreted Language: No compilation needed, which speeds up development.
27. Explain scope resolution in Python?
Scope resolution in Python (LEGB Rule):
Python resolves variable names using the LEGB rule, which stands for:
- Local: Checks the innermost scope (inside functions).
- Enclosing: Looks for variables in enclosing functions (nested).
- Global: Searches the global scope (module-level variables).
- Built-in: Finally, checks the built-in functions and variables.
Example of scope resolution:
1x = 50 # Global scope
2
3def outer():
4 x = 25 # Enclosing scope
5 def inner():
6 x = 10 # Local scope
7 print(x) # Output: 10
8 inner()
9
10outer()
11print(x) # Output: 50 (Global)
28. Is indentation required in Python?
Yes, indentation is required in Python. Unlike many other programming languages that use braces or keywords to define code blocks, Python relies on indentation to determine the structure and hierarchy of the code. Proper indentation is crucial because it defines blocks of code, such as loops, functions, and conditional statements.
29. What are *args and *kwargs?
*args and **kwargs are special syntax in Python used to pass a variable number of arguments to a function.
1. *args (Non-keyword arguments):
- Definition: *args allows a function to accept any number of positional arguments (non-keyword arguments).
- Usage: When used in a function definition, *args collects all extra positional arguments passed to the function and stores them in a tuple.
Example:
1def my_function(*args):
2 for arg in args:
3 print(arg)
4
5my_function(1, 2, 3, 4) # Output: 1 2 3 4
2. **kwargs (Keyword Arguments):
- Definition: **kwargs allows a function to accept any number of keyword arguments.
- Usage: **kwargs collects these keyword arguments into a dictionary.
Example:
1def my_function(**kwargs):
2 for key, value in kwargs.items():
3 print(f"{key}: {value}")
4
5my_function(name="Alice", age=30) # Output: name: Alice, age: 30
30. What is type conversion in Python?
Type conversion in Python refers to converting one data type into another. Python provides both implicit and explicit type conversion mechanisms.
1. Implicit Type Conversion:
- Definition: Python automatically converts one data type to another whenever necessary without user intervention.
Example:
1x = 5 # Integer
2y = 2.5 # Float
3result = x + y # Python automatically converts x to float
4print(result) # Output: 7.5 (float)
2. Explicit Type Conversion (Type Casting):
- Definition: In explicit type conversion, also known as type casting, the user manually converts one data type into another using built-in functions.
- Common Functions:
- int(): Converts to an integer.
- float(): Converts to a float.
- str(): Converts to a string.
- list(), tuple(), set(): Convert to respective collections.
Example:
1x = "100"
2y = int(x) # Explicitly convert string to integer
3print(y) # Output: 100 (integer)
31. How are comments written in Python?
In Python, comments are written using the # symbol. Anything after # on the same line is ignored by the Python interpreter, allowing you to include notes or explanations in your code without affecting its execution.
1# This is a single-line comment
2print("Hello, World!") # This prints a greeting message
32. How are Python dictionaries implemented?
Python dictionaries are implemented as hash tables, which provide fast and efficient data retrieval. A Python dictionary stores data in key-value pairs, where each key is unique, and values can be of any data type.
Key features of Python dictionaries:
- Hash Table: Under the hood, Python dictionaries use a hash table to map keys to values. Each key is hashed to produce an index in the hash table, where the corresponding value is stored.
- Unique Keys: Keys must be immutable (e.g., strings, numbers, tuples), and each key must be unique.
- Constant-Time Access: Due to the hash table implementation, dictionary lookups (e.g., accessing or modifying a value by its key) have an average time complexity of O(1), making them very efficient.
Dictionary Structure:
- Keys: Used to uniquely identify the data (must be immutable).
- Values: Data stored corresponding to each key (can be mutable or immutable).
Example:
1my_dict = {"name": "Alice", "age": 30, "city": "New York"}
2print(my_dict["name"]) # Output: Alice
33. What is __init__() in Python?
In Python, __init__() is a special method, also known as a constructor, used to initialize objects when a class is instantiated. It is automatically called when a new object of the class is created. The __init__() method allows you to define and set up initial values for the object's attributes.
Syntax:
1class MyClass:
2 def __init__(self, attribute1, attribute2):
3 self.attribute1 = attribute1
4 self.attribute2 = attribute2
34. Difference between mutable and immutable in Python?
In Python, mutable and immutable refer to whether an object's value can be modified after it has been created.
1. Mutable data types:
- Definition: Mutable objects can be changed after they are created, meaning their values can be modified in place.
- Examples:
- Lists (list)
- Dictionaries (dict)
- Sets (set)
- Bytearrays (bytearray)
- Behavior: Changes made to a mutable object will reflect across all references to that object.
Example:
1my_list = [1, 2, 3]
2my_list[0] = 10 # Modifying the list
3print(my_list) # Output: [10, 2, 3]
2. Immutable Data Types:
- Definition: Immutable objects cannot be changed after they are created. If you want to modify the value, you must create a new object.
- Examples:
- Strings (str)
- Tuples (tuple)
- Integers (int)
- Floats (float)
- Booleans (bool)
- Behavior: Since these objects cannot be changed, any operation that appears to modify them will actually create a new object.
Example:
1my_tuple = (1, 2, 3)
2my_tuple[0] = 10 # This will raise an error since tuples are immutable
35. What is monkey patching in Python?
Monkey patching in Python refers to the dynamic modification of a class or module at runtime. This allows developers to change or extend the behavior of existing classes or modules without altering their original source code.
Key characteristics:
- Runtime Modification: Changes are applied while the program is running.
- Directly Modifying Attributes: You can change methods, functions, or attributes of an existing class or module.
- Common Use Cases: It is often used for testing or temporary fixes, although it's generally considered bad practice in production code due to potential maintainability issues.
Example of Monkey Patching:
1class MyClass:
2 def greet(self):
3 return "Hello!"
4
5# Original behavior
6obj = MyClass()
7print(obj.greet()) # Output: Hello!
8
9# Monkey patching the greet method
10def new_greet():
11 return "Hi!"
12
13MyClass.greet = new_greet
14
15# Modified behavior after monkey patching
16print(obj.greet()) # Output: Hi!
In this example, we dynamically modify the greet method of MyClass at runtime by assigning a new function new_greet to it.
Advanced Python interview questions
36. What is the Python
The with statement in Python is designed to simplify the management of resources such as file handling, database connections, or locks. It ensures that resources are properly acquired and released, even if exceptions occur during their usage.
Key purpose:
Automatic Resource Management: The with statement is primarily used for managing resources that need to be cleaned up after use, such as closing a file or releasing a lock, without explicitly needing to call methods like close().
Example of file handling:
1with open("example.txt", "r") as file:
2 content = file.read()
3 print(content)
37. Array vs list in Python
The key difference between arrays and lists are as follow:
- Data Type:
- List: Can store elements of different types.
- Array: Stores elements of a single, fixed data type.
- Usage:
- List: Used for general-purpose storage of data that may be heterogeneous.
- Array: Used when performance and memory efficiency are crucial, especially for large numerical datasets.
- Performance:
- List: Slower for large datasets because of its flexibility.
- Array: Faster for numerical operations and large datasets due to type uniformity.
- Modules:
- List: No external module required (built-in).
- Array: Requires the array module or libraries like NumPy for advanced use.
38. What are unit tests in Python?
Unit tests in Python refer to a type of software testing where individual units or components of a program (such as functions, methods, or classes) are tested to ensure they work as expected. Python provides a built-in framework called unittest for writing and running unit tests, allowing developers to verify the correctness of their code.
Key features of unit testing:
- Isolating Code: Unit tests isolate each part of the program and verify its functionality independently.
- Automated Testing: Python's unittest framework enables automated testing, making it easier to repeatedly run tests as code evolves.
- Regression Testing: Unit tests help ensure that new code changes don't break existing functionality.
40. How to delete a file in Python?
To delete a file in Python, you can use the os.remove() or os.unlink() function from the built-in os module. Both functions work the same way to remove a file from the file system.
Steps to delete a File:
- Import the os module.
- Use os.remove() or os.unlink() to delete the file by specifying its file path.
1import os
2
3# Specify the file path
4file_path = "example.txt"
5
6# Delete the file
7if os.path.exists(file_path):
8 os.remove(file_path)
9 print(f"{file_path} has been deleted.")
10else:
11 print(f"{file_path} does not exist.")
41. What is polymorphism in Python?
Polymorphism in Python refers to the ability of different objects to be processed in the same way, even if they belong to different classes. It allows functions or methods to work on objects of different types, as long as they share the same method or attribute name. Polymorphism is a key concept in object-oriented programming (OOP) that enhances flexibility and reusability.
Types of polymorphism in Python:
1. Method Polymorphism (Function Overloading):
- Example:
- Different classes can implement the same method, allowing objects of these classes to be treated uniformly. The same function can be used for different types of objects, as long as those objects implement the expected behavior.
1class Dog:
2 def speak(self):
3 return "Woof!"
4
5class Cat:
6 def speak(self):
7 return "Meow!"
8
9def animal_sound(animal):
10 print(animal.speak())
11
12# Using polymorphism to call the same method on different objects
13dog = Dog()
14cat = Cat()
15
16animal_sound(dog) # Output: Woof!
17animal_sound(cat) # Output: Meow!
2. Polymorphism with Inheritance:
- Subclasses can override methods of the parent class to provide specific implementations. This allows objects of the subclass to behave differently, even when the parent class method is called.
Example:
1class Animal:
2 def speak(self):
3 pass
4
5class Dog(Animal):
6 def speak(self):
7 return "Woof!"
8
9class Cat(Animal):
10 def speak(self):
11 return "Meow!"
12
13# Calling the overridden method
14animals = [Dog(), Cat()]
15for animal in animals:
16 print(animal.speak())
42. What is Encapsulation in Python?
Encapsulation in Python is an object-oriented programming (OOP) concept that restricts direct access to an object’s internal data and methods, allowing controlled access through public methods. This hides the internal workings of an object and prevents accidental or unauthorized modifications. In Python, encapsulation is achieved by defining variables and methods as public, protected, or private.
43. What are the data types in python?
Data types in Python define the kind of data a variable can hold, such as integers (int), floating-point numbers (float), strings (str), and more. Python also has collections like lists (list), tuples (tuple), dictionaries (dict), and sets (set). These types help in storing, manipulating, and working with data efficiently based on its nature and structure.
44. What are the sets in python?
A set in Python is an unordered collection of unique elements, meaning it does not allow duplicate values. Sets are mutable, allowing you to add or remove elements after their creation. However, the elements themselves must be immutable (e.g., numbers, strings, tuples).
Key features of sets:
- Unique Elements: No duplicate values allowed.
- Unordered: Elements have no defined order, and you cannot access them via an index.
- Mutable: You can add or remove elements.
Example of a set:
1my_set = {1, 2, 3, 4, 4} # Duplicates are automatically removed
2print(my_set) # Output: {1, 2, 3, 4}
45. What is function annotations in Python?
Function annotations provide metadata about the types of function parameters and return values. They do not enforce types but serve as hints for developers.
1def greet(name: str) -> str:
2 return f"Hello, {name}"
46. What is exception groups in Python?
Exception groups, introduced in Python 3.11, allow multiple exceptions to be raised and handled together, making error handling more flexible when dealing with multiple issues simultaneously.
47. What is walrus operator (:=)?
The walrus operator allows you to assign a value to a variable within an expression, enabling concise and readable code.
1if (n := len([1, 2, 3])) > 2:
2 print(n) # Output: 3
48. What is Python switch statement?
Python doesn't have a native switch statement, but you can simulate it using dictionaries and functions.
1def switch_case(day):
2 switcher = {
3 1: "Monday",
4 2: "Tuesday",
5 3: "Wednesday"
6 }
7 return switcher.get(day, "Invalid day")
49. How to display the current time in Python?
Here is the method to display current time:
1from datetime import datetime
2print(datetime.now().strftime("%H:%M:%S"))
50. What is Zip Function?
The zip() function combines elements from multiple iterables (lists, tuples, etc.) into tuples, creating pairs from corresponding positions.
1a = [1, 2, 3]
2b = ['a', 'b', 'c']
3print(list(zip(a, b))) # Output: [(1, 'a'), (2, 'b'), (3, 'c')]
Related Articles
Sign-in First to Add Comment
Leave a comment 💬
All Comments
No comments yet.