Python Interview FAQ
Python Interview FAQ
1. Easy to Learn and Use: Python has a simple syntax which is easy to read and write,
making it a beginner-friendly language.
2. Interpreted Language: Python code is executed line by line, which helps in easy
debugging and dynamic typing.
3. Versatile and Portable: Python runs on various platforms (Windows, macOS, Linux)
without any changes in the code.
4. Extensive Library Support: Python has a vast standard library that supports a range
of operations from web development to machine learning.
5. Object-Oriented: Python supports both procedural and object-oriented programming
paradigms, promoting reusability and modularity.
1. Mutability: Lists are mutable (modifiable), while tuples are immutable (cannot be
modified).
2. Syntax: Lists use square brackets ([ ]), while tuples use parentheses (( )).
3. Performance: Tuples are faster to access and iterate compared to lists.
4. Use Cases: Lists are used when data can change, tuples are used for fixed data.
5. Methods: Lists have more built-in methods for modification (like append, remove),
tuples have fewer methods.
1. Definition: A namespace is a container that holds the names of variables and their
corresponding objects.
2. Types: There are four types—local, enclosing, global, and built-in namespaces.
3. Scope: The scope of a variable determines where it can be accessed (local, global,
etc.).
4. global and nonlocal: Keywords used to modify variables in the global and
enclosing scopes respectively.
5. Avoiding Conflicts: Namespaces help in organizing and avoiding naming conflicts in
the code.
1. Shallow Copy: Creates a new object but inserts references into it to the objects found
in the original.
2. Deep Copy: Creates a new object and recursively copies all objects found in the
original, ensuring no shared references.
3. Usage: copy() function is used for shallow copy, and deepcopy() from the copy
module is used for deep copy.
4. Mutable Objects: Changes in mutable objects like lists affect the shallow copy but
not the deep copy.
5. Performance: Deep copy is slower and consumes more memory compared to
shallow copy due to full replication.
1. Instance Reference: self refers to the instance of the class, allowing access to its
attributes and methods.
2. Not a Keyword: Although a convention, self is not a keyword and can be replaced
with any other name.
3. Instance Variables: Used to differentiate between instance variables and local
variables within methods.
4. First Argument: Always the first parameter in instance methods, representing the
object itself.
5. Access: Allows the use of attributes and methods across different methods in the
same class.
1. Concise Syntax: A syntactic construct for creating lists based on existing lists in a
concise way.
2. Basic Structure: [expression for item in iterable if condition] is the
basic format.
3. Filtering: Optional if clause can be used for filtering elements.
4. Nested Comprehension: Supports nested comprehensions for creating
multidimensional lists.
5. Performance: Faster and more readable compared to traditional loops for creating
lists.
14. What is a generator in Python?
1. Definition: A generator is a special type of iterator that generates values on the fly
and maintains state between iterations.
2. Syntax: Created using functions and the yield keyword instead of return.
3. Memory Efficient: Generators produce items one at a time and only when required,
which saves memory.
4. Lazy Evaluation: Values are computed lazily, allowing large data sequences to be
generated efficiently.
5. Use Cases: Useful for handling large datasets or streams of data where full list
generation would be memory-intensive.
1. Definition: GIL is a mutex that protects access to Python objects, preventing multiple
native threads from executing Python bytecodes at once.
2. Impact on Multithreading: Limits the execution of threads in Python, meaning only
one thread can execute Python code at a time.
3. CPU-bound vs I/O-bound: GIL affects CPU-bound threads more severely, while
I/O-bound threads are less impacted.
4. Workarounds: Use multiprocessing or external libraries like concurrent.futures
for parallelism.
5. Alternative Implementations: Other Python implementations like Jython and
IronPython do not have GIL.
17. What are Python decorators and how are they used?
20. What is the difference between append() and extend() in Python lists?
1. append(): Adds its argument as a single element to the end of the list.
2. extend(): Adds each element of its argument (a list or iterable) to the end of the list.
3. Argument Type: append() takes a single element, extend() takes an iterable (list,
tuple, set).
4. Modification: append() increases the list length by 1, extend() increases it by the
number of elements in the iterable.
5. Use Cases: Use append() for adding single items, extend() for concatenating
multiple elements.
21. What is the difference between local, global, and nonlocal keywords in Python?
1. Definition: Built-in functions are pre-defined functions provided by Python that can
be used without importing any module.
2. Examples:
o len(): Returns the length of an object.
o type(): Returns the type of an object.
o print(): Prints the specified message to the console.
o input(): Takes user input as a string.
o sum(): Sums up all items in an iterable.
3. Versatility: These functions simplify common tasks and are optimized for
performance.
4. No Import Required: They can be used directly in the code without importing any
module.
5. Extensible: Additional built-in functions can be created by defining custom functions
or using libraries.
1. Combining Iterables: The zip() function takes iterables (like lists, tuples) and
returns an iterator of tuples, pairing elements with the same index.
2. Length Mismatch: If the input iterables are of different lengths, the result is
truncated to the shortest input iterable.
3. Unpacking: The result of zip() can be unpacked into separate iterables using the *
operator.
4. Common Use Case: Often used to pair keys and values or to loop through multiple
iterables simultaneously.
5. Return Type: Returns a zip object, which can be converted into a list or tuple.
1. Definition: Applies a given function to all items in an input iterable (like a list) and
returns a map object.
2. Syntax: map(function, iterable) is the basic syntax.
3. Multiple Iterables: Can take multiple iterables as arguments, applying the function to
corresponding elements.
4. Return Type: Returns a map object, which can be converted into a list, tuple, etc.
5. Use Case: Commonly used for element-wise transformations, like converting all
items in a list to uppercase.
1. Definition: Filters elements from an iterable based on a function that returns either
True or False.
2. Syntax: filter(function, iterable) is the basic syntax.
3. Return Type: Returns a filter object, which can be converted to a list, tuple, etc.
4. Use Case: Used to extract elements that satisfy a certain condition, like extracting
even numbers from a list.
5. Function Requirement: The function should return a boolean value, deciding
whether the item should be included.
29. What is the purpose of the reduce() function and where is it used?
1. Definition: String methods are built-in functions that perform various operations on
strings.
2. Examples:
o lower(): Converts all characters to lowercase.
o upper(): Converts all characters to uppercase.
o split(): Splits a string into a list based on a delimiter.
o join(): Joins elements of a list into a single string with a specified delimiter.
o replace(): Replaces a substring with another substring.
3. Immutability: Strings are immutable, so these methods return new strings without
modifying the original.
4. Format Methods: format() and f-string (f"{variable}") are used for dynamic
string formatting.
5. Use Cases: These methods simplify text processing and manipulation tasks.
1. Definition: This is a conditional statement that checks if a Python file is being run as
the main program or being imported as a module.
2. Purpose: It allows code inside the block to run only when the script is executed
directly, not when imported into another module.
3. Common Use Case: Useful for writing reusable modules and scripts where some
code is only executed if the file is run directly.
4. __name__: When the script is executed, __name__ is set to "__main__"; when
imported, it is set to the module's name.
5. Modular Programming: Encourages better modularity and reusability by keeping
script execution separate from module functionality.
1. Purpose: The open() function is used to open a file and return a file object for
reading, writing, or appending.
2. Syntax: open(filename, mode) where mode can be 'r' (read), 'w' (write), 'a'
(append), and 'b' for binary files.
3. File Modes:
o 'r': Opens file for reading (default mode).
o 'w': Opens file for writing (overwrites existing content).
o 'a': Opens file for appending (adds new content to the end of the file).
o 'b': Binary mode, used for non-text files (like images).
4. Context Manager: Often used with the with statement to ensure proper closing of
files.
5. Return Value: Returns a file object, which can be used to read, write, or manipulate
the file.
1. Definition: A docstring is a string literal that appears right after the definition of a
function, method, class, or module to document its purpose.
2. Syntax: Defined using triple quotes """ immediately after the function or class
declaration.
3. Accessing Docstrings: Can be accessed using the __doc__ attribute of the function,
class, or module.
4. Use Case: Used to describe the functionality, inputs, outputs, and usage of a piece of
code.
5. Documentation Tools: Docstrings are used by documentation tools like Sphinx to
auto-generate documentation.
1. Iterable: An object capable of returning its elements one at a time, such as lists,
tuples, strings.
2. Iterator: An object representing a stream of data, created from an iterable using the
iter() function.
3. Methods: Iterators implement two methods: __iter__() (returns the iterator object)
and __next__() (returns the next item).
4. Exhaustion: Iterators can only be traversed once, unlike iterables that can be looped
multiple times.
5. Use Case: Useful for lazy evaluation where elements are fetched only when needed
(e.g., reading large files).
1. Definition: A class method is a method that is bound to the class rather than the
instance of the class.
2. Decorator: Defined using the @classmethod decorator.
3. First Parameter: Takes cls as the first parameter, representing the class itself.
4. Use Case: Often used for factory methods or methods that operate on class-level data
rather than instance data.
5. Accessing Class Variables: Can modify or access class-level variables and methods.
1. Definition: A static method is a method that doesn’t take self or cls as the first
parameter and doesn't depend on the instance or class.
2. Decorator: Defined using the @staticmethod decorator.
3. Use Case: Useful for utility functions that don’t modify class or instance state but are
logically related to the class.
4. No Access to Class/Instance Data: Unlike class methods and instance methods,
static methods don’t have access to cls or self.
5. Call Syntax: Can be called on an instance or directly on the class.
38. What is a metaclass in Python?
1. Definition: A metaclass is a class of a class that defines how a class behaves, similar
to how classes define the behavior of instances.
2. Purpose: Used to control the creation and behavior of classes, such as adding
methods or modifying class attributes.
3. Syntax: A class can have a metaclass by setting the __metaclass__ attribute or by
inheriting from a metaclass.
4. Use Case: Often used for implementing frameworks or APIs where custom class
creation behavior is needed.
5. Example: type is the default metaclass in Python.
1. Definition: Properties allow you to define methods that behave like attributes,
enabling encapsulation and control over attribute access.
2. @property Decorator: Used to define a getter method that behaves like an attribute.
3. Setter and Deleter: You can define corresponding @attribute_name.setter and
@attribute_name.deleter for setting and deleting the property.
4. Use Case: Allows for validation, calculation, or formatting when accessing or
modifying attributes.
5. Example: Provides a cleaner and more Pythonic interface than getter and setter
methods.
1. Definition: Magic methods are special methods that start and end with double
underscores (__method__), also known as dunder methods.
2. Examples:
o __init__: Initializes a new object.
o __str__: Returns a string representation of the object.
o __len__: Returns the length of the object.
o __add__: Defines the behavior of the + operator for objects.
o __eq__: Defines the behavior of the equality == operator.
3. Operator Overloading: Allows custom objects to support standard operators like +,
*, or comparison operators.
4. Custom Object Behavior: Magic methods control how objects behave in common
operations like printing, adding, or comparing.
5. Built-in Functions: Magic methods integrate custom objects with Python's built-in
functions (like len(), str()).
1. Definition: Method overloading is a feature where the same method name can have
different behaviors based on the number or types of parameters.
2. Not Directly Supported: Python does not support method overloading in the
traditional sense like other languages (e.g., Java or C++).
3. Default Arguments: Overloading can be simulated using default arguments to vary
method behavior.
4. Type Checking: Functionality can also be altered by explicitly checking the types or
number of arguments inside the method.
5. Use Case: Used to provide different behaviors for a method depending on how many
or what types of arguments are passed.
1. Instance Reference: self refers to the instance of the class and is used to access the
instance’s attributes and methods.
2. Not a Keyword: It’s a convention, not a reserved keyword, and can be named
differently (though not recommended).
3. First Parameter: Always the first parameter in instance methods, allowing each
instance to keep track of its own data.
4. Explicit Passing: When a method is called on an instance, self is passed
automatically by Python.
5. Attribute Access: Used to differentiate between instance variables and method
parameters within class methods.
1. Old Style (%): Uses the % operator for formatting, like "%s is %d years old" %
("Alice", 30).
2. str.format(): Uses curly braces {} as placeholders, like "{} is {} years
old".format("Alice", 30).
3. f-Strings: Introduced in Python 3.6, use the f prefix and curly braces to embed
expressions, like f"{name} is {age} years old".
4. Template Strings: Defined in the string module, using $ as placeholders for
variables, like Template("$name is $age years old").
5. Flexibility: f-strings are the most efficient and readable, supporting inline expressions
and more complex formatting options.
1. Automatic Memory Management: Python uses a private heap space for memory
allocation, managed by the Python memory manager.
2. Garbage Collection: Python has an automatic garbage collector to recycle unused
memory.
3. Reference Counting: Each object in Python has a reference count, and when it drops
to zero, the memory is deallocated.
4. Cycle Detection: The garbage collector detects and cleans up circular references that
reference counting cannot handle.
5. Memory Pools: Python maintains several pools of memory for different object types
and sizes, optimizing memory usage.
49. What is a Python set and what are its key features?
1. Definition: A closure is a nested function that remembers the values from its
enclosing scope even after the outer function has finished executing.
2. Use Case: Used to create function factories or data hiding, where the inner function
has access to variables from the outer function.
3. Syntax: A closure is formed when an inner function references variables from its
outer function and the outer function returns the inner function.
4. Example: Defining a function that returns another function with bound parameters.
5. Advantages: Useful for maintaining state or data between function calls without
using global variables.
1. sort(): A list method that modifies the list in place, sorting its elements.
2. sorted(): A built-in function that returns a new sorted list from any iterable, leaving
the original iterable unchanged.
3. Return Value: sort() returns None, while sorted() returns a new list.
4. Custom Sorting: Both support custom sorting by using the key parameter for
specifying a sorting function.
5. Stability: Both methods maintain the relative order of records with equal keys (stable
sorting).
1. Definition: The itertools module provides a collection of tools for efficient looping
and iteration.
2. Common Functions:
o count(): Infinite counter starting from a specified number.
o cycle(): Repeats an iterable indefinitely.
o repeat(): Repeats an object a specified number of times.
o combinations(): Generates all possible combinations of a given length.
o permutations(): Generates all possible permutations of a given length.
3. Use Cases: Useful for complex iteration tasks like combinatorics and producing
Cartesian products.
4. Memory Efficiency: Returns iterators that produce results lazily, saving memory.
5. Chaining: Supports chaining multiple iterators together with chain().
1. Union (|): Combines all elements from two sets, removing duplicates.
2. Intersection (&): Returns elements common to both sets.
3. Difference (-): Returns elements in the first set but not in the second.
4. Symmetric Difference (^): Returns elements that are in either of the sets but not in
both.
5. Subset/Superset (<=/>=): Checks if all elements of one set are present in another or
vice versa.