Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
5 views

Python Interview FAQ

Uploaded by

tomarakash7800
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Python Interview FAQ

Uploaded by

tomarakash7800
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

1. What are Python's key features?

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.

2. What are Python's data types?

1. Numeric Types: Integers (int), floating-point numbers (float), and complex


numbers (complex).
2. Sequence Types: Strings (str), lists (list), and tuples (tuple).
3. Mapping Type: Dictionaries (dict), which store key-value pairs.
4. Set Types: Sets (set) and frozensets (frozenset), which hold unique, unordered
elements.
5. Boolean Type: Boolean values (bool) representing True or False.

3. What is the difference between list and tuple?

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.

4. What is a Python decorator?

1. Functionality Extension: Decorators are used to add additional functionality to


existing functions without modifying their structure.
2. Syntax: Decorators use the @decorator_name syntax above the function definition.
3. Use Cases: Commonly used for logging, access control, and memoization.
4. Higher-Order Functions: Decorators are higher-order functions as they take another
function as input and return a new function.
5. Nested Functions: Decorators often use nested functions to wrap the original
function's behavior.

5. What are Python namespaces?

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.

6. What is the difference between deepcopy and shallow copy?

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.

7. What is a Python lambda function?

1. Anonymous Function: A lambda function is a small anonymous function defined


using the lambda keyword.
2. Syntax: lambda arguments: expression is the basic syntax of a lambda function.
3. Single Expression: Lambda functions can only contain a single expression, unlike
regular functions.
4. Usage: Commonly used for short, throwaway functions, especially in higher-order
functions like map, filter, and sorted.
5. No Statements: Lambda functions cannot contain statements like loops, return, or
print.

8. What is the purpose of the self keyword in classes?

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.

9. What is the difference between break, continue, and pass?

1. break: Terminates the loop and exits out of it completely.


2. continue: Skips the current iteration and moves to the next iteration of the loop.
3. pass: A null operation, often used as a placeholder where a statement is syntactically
required but no action is needed.
4. Usage: break is used for early termination, continue for skipping, and pass for
empty bodies.
5. Control Flow: All three control the flow of loops, but each serves a different purpose
in managing execution.

10. What is Python's __init__ method?

1. Constructor: __init__ is a special method called a constructor, automatically


invoked when a new object is created.
2. Object Initialization: Used to initialize the object’s state by assigning initial values
to object attributes.
3. Not Mandatory: It's not mandatory to define an __init__ method in a class unless
specific initializations are required.
4. Arguments: Can accept arguments other than self to initialize object attributes with
specific values.
5. Multiple Constructors: Python doesn’t support method overloading directly, but
default arguments can be used to achieve similar behavior.

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

1. == Operator: Compares the values of two objects for equality.


2. is Operator: Compares the memory addresses of two objects to check if they are the
same instance.
3. Usage: == is used for value comparison, while is is used for identity comparison.
4. Example: a == b returns True if values are the same; a is b returns True if both a
and b point to the same object.
5. Immutable Objects: For small integers and strings, is may sometimes give True for
objects with the same value due to interning, but it’s not reliable for general use.

12. What are Python's built-in data structures?

1. List: Ordered, mutable, and allows duplicate elements.


2. Tuple: Ordered, immutable, and allows duplicate elements.
3. Dictionary: Unordered, mutable, and stores key-value pairs.
4. Set: Unordered, mutable, and stores unique elements.
5. String: Ordered, immutable sequence of characters.

13. What is list comprehension in Python?

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.

15. What are Python's exception handling keywords?

1. try: Block of code to test for exceptions.


2. except: Block of code to handle the exception.
3. else: Executes if no exceptions are raised in the try block.
4. finally: Executes regardless of whether an exception is raised or not, useful for
cleanup actions.
5. raise: Used to manually trigger an exception within a code block.

16. What is the Global Interpreter Lock (GIL) in Python?

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?

1. Definition: Decorators are a way to modify or enhance the behavior of a function or


method without modifying its code.
2. Function Wrapping: They take a function, add some functionality, and return it.
3. Syntax: Defined using the @decorator_name syntax before the function definition.
4. Use Cases: Commonly used for logging, authentication, caching, and timing
functions.
5. Chaining: Multiple decorators can be chained together to apply several layers of
modifications.

18. What is the purpose of the with statement in Python?

1. Context Management: Ensures resources are properly managed by acquiring and


releasing them as necessary.
2. Automatic Cleanup: Handles resource management automatically, even if
exceptions occur.
3. Syntax: with expression as variable: is the basic format.
4. Common Use Cases: Used with file operations, locks, and connections to ensure they
are properly closed after usage.
5. Custom Context Managers: Can be created using the __enter__ and __exit__
methods in a class.

19. How does Python's garbage collection work?

1. Reference Counting: Python primarily uses reference counting to keep track of


object usage.
2. Cycle Detection: The garbage collector detects and cleans up circular references that
reference counting cannot handle.
3. gc Module: The gc module can be used to interact with the garbage collector (e.g.,
enabling/disabling).
4. Automatic Cleanup: The garbage collector runs automatically to reclaim memory
occupied by unreachable objects.
5. Customization: Can be tuned or controlled for performance optimization in certain
applications.

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. local: Refers to variables defined within the current function scope.


2. global: Declares a variable as global, allowing access and modification of variables
outside the current scope.
3. nonlocal: Used inside nested functions to refer to variables from the enclosing (non-
global) scope.
4. Use Case of global: Used to modify a global variable within a function.
5. Use Case of nonlocal: Useful for modifying variables in the outer function from
within an inner function.

22. What are Python’s built-in functions? Name a few.

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.

23. What is the purpose of the zip() function?

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.

24. What are *args and **kwargs in Python?

1. *args: Allows a function to accept any number of positional arguments as a tuple.


2. **kwargs: Allows a function to accept any number of keyword arguments as a
dictionary.
3. Use Case of *args: Useful when you don’t know the number of arguments in
advance.
4. Use Case of **kwargs: Useful when you want to handle named arguments
dynamically.
5. Combining: *args and **kwargs can be used together in a function definition,
allowing for maximum flexibility.

25. What is a module in Python?

1. Definition: A module is a file containing Python code, such as functions, classes, or


variables, that can be imported and used in other Python programs.
2. Creating Modules: Any .py file can be considered a module.
3. Importing Modules: Modules can be imported using the import statement.
4. Standard and User-defined: Python has standard modules (like os, sys) and user-
defined modules created by users.
5. Reusability: Modules promote reusability and code organization by dividing large
programs into manageable pieces.

26. What are Python's standard libraries?


1. Definition: A standard library is a collection of modules that come bundled with
Python, providing standardized functionality.
2. Examples:
o os: Interact with the operating system.
o sys: Access system-specific parameters and functions.
o math: Provides mathematical functions like sqrt, pow.
o datetime: Manipulate dates and times.
o json: Encode and decode JSON data.
3. No Installation Required: These libraries are part of Python’s default installation.
4. Versatility: Cover a wide range of applications from file I/O to web scraping.
5. Documentation: Well-documented with usage examples and reference material.

27. How does the map() function work?

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.

28. What is the purpose of the filter() function?

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: reduce() applies a specified function cumulatively to the items of an


iterable, from left to right, reducing the iterable to a single value.
2. Syntax: reduce(function, iterable) is the basic syntax, where the function must
take two arguments.
3. Return Type: Returns a single accumulated value.
4. Common Use Cases: Used for cumulative operations like summing or finding the
product of all elements in a list.
5. Module: It is part of the functools module and needs to be imported using from
functools import reduce.

30. What are Python's string methods? Name a few.

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.

31. What is __name__ == "__main__" in Python?

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.

32. What is the open() function in Python?

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.

33. What are docstrings in Python?

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.

34. What is monkey patching in Python?

1. Definition: Monkey patching refers to the practice of dynamically modifying or


extending modules or classes at runtime.
2. Use Case: Often used in testing to mock or modify behavior temporarily.
3. Dynamic Nature: Python allows this because it's a dynamically typed language.
4. Caution: It can make code difficult to debug and maintain since behavior is altered at
runtime.
5. Example: You can modify the behavior of a method by reassigning it after importing
the module.

35. What are Python iterators and iterables?

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).

36. What is a Python class method?

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.

37. What is a static method in Python?

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.

39. What is a property 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.

40. What is super() in Python?

1. Definition: super() is used to call methods from a parent or superclass in a derived


class.
2. Purpose: It allows you to avoid explicit naming of the parent class, making the code
more maintainable.
3. Common Use Case: Used in constructors (__init__()) to ensure proper
initialization of the parent class.
4. Multiple Inheritance: It’s especially useful in multiple inheritance scenarios to
ensure all parent classes are initialized correctly.
5. Syntax: super().method_name() is the typical syntax used to invoke a method from
the parent class.

41. What are Python's magic 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()).

42. What is method overloading in Python?

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.

43. What is the self parameter in Python classes?

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.

44. What is the purpose of the enumerate() function in Python?

1. Definition: The enumerate() function adds a counter to an iterable and returns it as


an enumerate object.
2. Syntax: enumerate(iterable, start=0) where start is the initial value of the
counter.
3. Use Case: Commonly used in for loops to access both the index and the value of
items in a list or other iterable.
4. Return Type: Returns an enumerate object,

45. What is the collections module in Python?

1. Definition: The collections module provides specialized data structures such as


named tuples, deque, Counter, OrderedDict, and defaultdict.
2. namedtuple: Allows you to create tuple subclasses with named fields, making tuples
more readable and accessible.
3. deque: A double-ended queue that supports fast appends and pops from both ends.
4. Counter: A dictionary subclass for counting hashable objects, useful for tallying
elements in an iterable.
5. defaultdict: A dictionary-like object that provides a default value for nonexistent
keys, avoiding KeyError.

46. What are Python's string formatting 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.

47. How does Python's memory management work?

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.

48. What is the purpose of the eval() function?

1. Definition: eval() parses the expression passed to it as a string and executes it as a


Python expression.
2. Use Case: Useful for dynamically executing expressions inputted by the user, like
mathematical calculations.
3. Syntax: eval(expression, globals=None, locals=None), where expression is
the string to be evaluated.
4. Security Risk: Using eval() can be dangerous as it executes arbitrary code, leading
to security vulnerabilities.
5. Alternative: Consider using ast.literal_eval() for safer evaluation of
expressions, especially when handling user inputs.

49. What is a Python set and what are its key features?

1. Definition: A set is an unordered collection of unique and immutable elements.


2. Mutable: While the elements inside a set are immutable, the set itself is mutable and
can be modified.
3. Operations: Supports mathematical operations like union ( |), intersection (&),
difference (-), and symmetric difference (^).
4. Elimination of Duplicates: Automatically removes duplicate entries, making it
useful for filtering unique items.
5. Built-in Methods: Provides methods like add(), remove(), discard(), and pop()
for element manipulation.

50. What are Python's slicing operations?

1. Definition: Slicing is used to access a range of elements in sequences like lists,


tuples, and strings.
2. Syntax: sequence[start:stop:step] is the basic slicing syntax.
3. Default Values: If start is omitted, it defaults to the beginning; if stop is omitted, it
defaults to the end; step defaults to 1.
4. Negative Indexing: Allows access to elements from the end of the sequence, such as
sequence[-1] for the last element.
5. Use Cases: Commonly used for reversing sequences, extracting sublists, and skipping
elements.

51. What is a Python closure?

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.

52. What is the difference between sorted() and sort() in Python?

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).

53. What is the itertools module in Python?

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().

54. What is the purpose of the assert statement in Python?

1. Definition: The assert statement is used for debugging purposes to test if a


condition is true, raising an AssertionError if it is not.
2. Syntax: assert condition, "Optional error message".
3. Use Case: Commonly used to validate assumptions made in the code during
development.
4. Disabling Assertions: Can be globally disabled with the -O (optimize) switch while
running the Python interpreter.
5. Not for Production: Should not be used for runtime checks or input validation in
production code as it can be bypassed.

55. What is a lambda function and how is it used?

1. Definition: A lambda function is an anonymous function defined using the lambda


keyword, with no name and a single expression.
2. Syntax: lambda arguments: expression.
3. Use Cases: Useful for short-lived, small functions that are passed as arguments to
higher-order functions like map(), filter(), and sorted().
4. Limitations: Can only contain a single expression and cannot include statements or
multiple expressions.
5. Readability: Should be used sparingly as they can make code harder to read
compared to regular functions.

56. What is a Python virtual environment and why is it used?

1. Definition: A virtual environment is an isolated Python environment that allows you


to install packages and dependencies for a project without affecting the global Python
installation.
2. Creation: Created using venv or virtualenv modules with the command python -m
venv myenv.
3. Activation: Activated with a script, such as source myenv/bin/activate on Unix
or myenv\Scripts\activate on Windows.
4. Use Case: Useful for managing dependencies for different projects, ensuring they do
not interfere with each other.
5. Deactivation: Can be deactivated with the command deactivate, returning to the
global Python environment.

57. What is the pass statement in Python?

1. Definition: The pass statement is a null operation, serving as a placeholder where


syntactically a statement is required, but no action is needed.
2. Use Case: Commonly used in places where code is yet to be written, such as stubbing
out functions, loops, or classes.
3. Avoid Syntax Errors: Helps to avoid syntax errors in code that is under
development.
4. No Operation: It doesn’t execute any action and has no effect on the program.
5. Readability: Improves readability by indicating that the block is intentionally left
empty.

58. What are Python’s set operations?

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.

You might also like