Ans. Python is a high-level, interpreted programming language known for its simplicity and readability. Key features include:
Ans. Python supports several built-in data types:
Ans. A decorator is a function that extends the behavior of another function without modifying it directly.
def decorator(func):
def wrapper():
print("Before function call")
func()
print("After function call")
return wrapper
@decorator
def say_hello():
print("Hello!")
say_hello()
Ans. Inheritance allows one class (child) to inherit attributes and methods from another (parent).
class Animal:
def speak(self):
print("Animal speaks")
class Dog(Animal):
def speak(self):
print("Dog barks")
dog = Dog()
dog.speak() # Outputs: Dog barks
Ans. A shallow copy creates a new object but not nested objects. A deep copy copies the object and all nested objects recursively.
Ans. Key differences include:
print
is a function in Python 3, not a statement.Ans. A lambda function is a small anonymous function defined with the lambda
keyword.
add = lambda x, y: x + y
print(add(3, 4)) # Outputs: 7
is
and ==
in Python?Ans. ==
checks if values are equal. is
checks if two references point to the same object in memory.
Ans. A generator uses yield
to return values one at a time. It can be paused and resumed, making it memory-efficient.
def my_generator():
yield 1
yield 2
yield 3
gen = my_generator()
print(next(gen)) # Outputs: 1
print(next(gen)) # Outputs: 2
Ans. Python's built-in data structures include:
Ans. Lists are mutable and can be changed after creation, whereas tuples are immutable and cannot be modified.
Ans. Python uses a private heap space and automatic garbage collection. The memory manager allocates memory and the garbage collector reclaims unused memory.
with
statement in Python?Ans. The with
statement is used to wrap the execution of a block with methods defined by a context manager. It ensures proper acquisition and release of resources.
with open('file.txt') as f:
data = f.read()
Ans. *args
is used to pass a variable number of positional arguments, while **kwargs
passes keyword arguments.
def func(*args, **kwargs):
print(args)
print(kwargs)
Ans. A module is a single Python file containing functions and classes. A package is a directory containing multiple modules and an __init__.py
file.
Ans. Python uses try
, except
, else
, and finally
blocks to handle exceptions.
try:
x = 1 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
Ans. Python uses the LEGB rule: Local, Enclosing, Global, Built-in to determine variable scope.
Ans. A shallow copy creates a new object but inserts references into it, whereas a deep copy creates a new object and recursively copies all objects inside it.
Ans. An iterator is an object that can be iterated upon using the __iter__()
and __next__()
methods.
Ans. A function is defined using def
and can be standalone. A method is a function associated with an object/class.
Ans. Python uses pip (Python Package Installer) to install and manage third-party packages.
pip install package-name
Ans. List comprehension is a concise way to create lists.
squares = [x**2 for x in range(5)]
Ans. Python provides several built-in functions like len()
, type()
, range()
, sum()
, max()
, min()
, etc.
Ans. global
is used to declare a global variable inside a function. nonlocal
is used in nested functions to refer to a variable in the nearest enclosing scope.
Ans. Use the open()
function and methods like read()
, readline()
, or iterate through the file object.
with open("file.txt", "r") as file:
content = file.read()
Ans. Magic methods (also called dunder methods) are special methods with double underscores like __init__
, __str__
, __len__
, __add__
, etc., used to customize object behavior.
pass
statement in Python?Ans. pass
is a placeholder statement used when no action is required. It helps define empty classes, functions, or loops.
del
, remove()
, and pop()
?Ans.
del
deletes by index or variable reference.remove()
removes the first matching value.pop()
removes and returns the item at a given index.Ans. Duck typing is a concept where the type or class of an object is less important than the methods or operations it supports. "If it walks like a duck and quacks like a duck, it’s a duck."
Ans. Popular frameworks include:
zip()
function?Ans. The zip()
function combines elements from multiple iterables into tuples.
list(zip([1, 2], ['a', 'b'])) # [(1, 'a'), (2, 'b')]
append()
and extend()
?Ans. append()
adds a single element to the end of a list, while extend()
adds multiple elements.
Ans. A virtual environment is an isolated Python environment that allows different projects to use different dependencies.
Ans. Python has three boolean operators: and
, or
, and not
.
Ans. Recursion is a process where a function calls itself. Useful for problems like factorial, Fibonacci, etc.
Ans. Python provides implicit and explicit type conversion using functions like int()
, str()
, float()
, etc.
@staticmethod
and @classmethod
?Ans. @staticmethod
doesn’t take class or instance as the first argument. @classmethod
takes cls
as the first parameter and can access class-level data.
Ans. You can use list.reverse()
method or slicing list[::-1]
.
Ans. Common string methods include upper()
, lower()
, strip()
, split()
, join()
, replace()
, and find()
.
Ans. Logical operators include and
, or
, and not
.
enumerate()
function?Ans. enumerate()
adds a counter to an iterable and returns it as an enumerate object.
Ans. Use multiple except
blocks or a tuple of exceptions in one block.
Ans. Bitwise operators include &
, |
, ^
, ~
, <<
, and >>
.
Ans. A concise way to create dictionaries.
{x: x**2 for x in range(3)}
__name__ == "__main__"
check?Ans. It checks whether the script is run directly or imported as a module.
Ans. Generators use yield
, creating iterators that are memory efficient. Iterators use __iter__()
and __next__()
.
map()
function?Ans. map()
applies a function to all items in an iterable.
filter()
function?Ans. filter()
filters elements based on a function that returns true or false.
reduce()
function?Ans. reduce()
is used to apply a function cumulatively to items (from functools).
Ans. Use sorted(list_of_tuples, key=lambda x: x[1])
Ans. GIL is a mutex that protects access to Python objects, allowing only one thread to execute at a time in CPython.
split()
and rsplit()
?Ans. split()
splits from the left, rsplit()
splits from the right.
Ans. Implement __iter__()
and __next__()
methods.
Ans. A metaclass is a class of a class that defines how classes behave.
Ans. Python code is compiled into bytecode (.pyc), which is then interpreted by the Python virtual machine.
Ans. Monkey patching refers to modifying or extending code at runtime.
Ans. Inherit from the base Exception
class.
class MyError(Exception):
pass
Ans. Popular libraries include Pandas, NumPy, Matplotlib, and SciPy.
Ans. Popular testing frameworks include unittest, pytest, and nose.
Ans. Use the pickle
or json
module for serialization and deserialization.
import json
data = json.dumps({"name": "Alice"})
obj = json.loads(data)
Ans. A concise way to create lists using a single line of code.
[x for x in range(5)] # [0, 1, 2, 3, 4]
Ans. A shallow copy copies references, while a deep copy creates a new copy of the objects.
Ans. It’s a concept where the type or class of an object is less important than the methods it defines ("If it walks like a duck...").
any()
and all()
functions?Ans. any()
returns True if any element is True, all()
returns True if all elements are True.
Ans. A small anonymous function defined using the lambda
keyword.
square = lambda x: x * x
Ans. Use the built-in open()
function with modes like 'r', 'w', 'a', and 'b'.
Ans. An object that properly manages resources using __enter__()
and __exit__()
methods, often used with with
statements.
is
and ==
?Ans. is
checks identity (same object), ==
checks equality (same value).
Ans. Common types include int, float, str, list, tuple, set, dict, and bool.
Ans. Use pip install package-name
.
args
and kwargs
?Ans. *args
allows variable number of positional arguments, **kwargs
allows variable keyword arguments.
Ans. Python does not support traditional method overloading. You can achieve similar behavior using default arguments or *args.
Ans. When a subclass provides a specific implementation of a method in its parent class.
Ans. Use efficient algorithms, built-in functions, libraries like NumPy, and avoid unnecessary computations.
Ans. A module is a single file; a package is a directory with an __init__.py
file containing multiple modules.
Ans. A function that takes another function and extends its behavior without modifying it directly.
Ans. Python uses a private heap space and garbage collection to manage memory.
collections
module?Ans. A module that implements specialized container datatypes like Counter
, defaultdict
, namedtuple
, etc.
Ans. A subclass of tuple with named fields for better readability and access by name.
Ans. Python allows you to specify variable and function types using annotations for better readability and tooling support.
def greet(name: str) -> str:
os
module?Ans. The os
module provides a way to interact with the operating system, such as file and directory manipulation.
Ans. Use os.listdir()
or glob.glob()
.
import os
os.listdir('.') # lists files in current directory
range()
and xrange()
?Ans. In Python 2, xrange()
is a generator and more memory efficient. In Python 3, only range()
exists and behaves like xrange()
.
with
statement?Ans. It simplifies resource management, automatically handling setup and teardown (e.g., file operations).
assert
statement?Ans. assert
is used for debugging to test if a condition is true. Raises AssertionError
if the condition is false.
int
and float
in Python?Ans. int
represents whole numbers, float
represents numbers with decimal points.
Ans. Use int()
for integers and float()
for floating-point numbers.
re
module?Ans. The re
module is used for working with regular expressions for pattern matching.
Ans. Python uses the LEGB rule: Local, Enclosing, Global, and Built-in scopes.
Ans. A closure is a function object that remembers values in enclosing scopes even if they are not in memory.
Ans. Python uses reference counting and garbage collection to manage memory.
pop()
and remove()
?Ans. pop()
removes an element at a specific index and returns it. remove()
removes the first occurrence of a value.
Ans. Slicing allows extracting parts of sequences using the syntax sequence[start:stop:step]
.
time
module used for?Ans. It provides functions for working with time, such as sleep()
, time()
, and ctime()
.
Ans. int
, float
, and complex
are the three built-in numeric types.
__init__.py
file?Ans. It is used to mark a directory as a Python package. It can also contain initialization code.
pass
statement?Ans. pass
is a placeholder for future code, used where syntactically some code is required but nothing is needed.
Ans. ==
, !=
, <
, >
, <=
, >=
.
Ans. A wheel (.whl) is a built package format for Python that allows faster installation than source distributions.
__str__()
and __repr__()
?Ans. __str__()
defines the human-readable string for an object, while __repr__()
defines the official string representation used for debugging.