Python Interview Questions and Answers
Last Updated : 04 Mar, 2025
Python is the most used language in top companies such as Intel, IBM,
NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many
more because of its robust performance and powerful libraries. To get
into these companies and organizations as a Python developer, we
need to master some important Python Interview Questions to crack
their Python Online Assessment Round and Python Interview Round.
We have prepared a list of the Top 50 Python Interview Questions
along with their answers to ace interviews.
Table of Content
Python Interview Questions for Freshers
Intermediate Python Interview Questions
Advanced Python Interview Questions & Answers
Python Interview Questions for Freshers
1. Is Python a compiled language or an interpreted language?
Python can be considered both compiled and interpreted, but in
different stages of its execution process.
1. Compilation: When you write Python code and run it, the Python
interpreter first compiles your source code (.py files) into an
intermediate form called bytecode (.pyc files). This bytecode is a
lower-level representation of your code, but it is still not directly
machine code. It’s something that the Python Virtual Machine (PVM)
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
can understand and execute.
acknowledge that you have read and understood our Cookie Policy & Privacy Policy Cookies are not
2. Interpretation : Afterin Python
collected code ismobile
the GeeksforGeeks compiled into bytecode, it is
applications.
executed by the Python Virtual
GotMachine
It ! (PVM), which is an
▲
interpreter. The PVM reads the bytecode and executes it line-by-line
at runtime, which is why Python is considered an interpreted
language in practice.
Some implementations, like PyPy, use Just-In-Time (JIT) compilation,
where Python code is compiled into machine code at runtime for faster
execution, blurring the lines between interpretation and compilation.
2. What is a dynamically typed language?
Typed languages are the languages in which we define the type of data
type and it will be known by the machine at the compile-time or at
runtime. Typed languages can be classified into two categories:
Statically typed languages: In this type of language, the data type of
a variable is known at the compile time which means the
programmer has to specify the data type of a variable at the time of
its declaration.
Dynamically typed languages: These are the languages that do not
require any pre-defined data type for any variable as it is interpreted
at runtime by the machine itself. In these languages, interpreters
assign the data type to a variable at runtime depending on its value.
3. Is Indentation Required in Python?
Yes, indentation is required in Python. A Python interpreter can be
informed that a group of statements belongs to a specific block of
code by using Python indentation. Indentations make the code easy to
read for developers in all programming languages but in Python, it is
very important to indent the code in a specific order.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our Cookie Policy & Privacy Policy Cookies are not
collected in the GeeksforGeeks mobile applications.
Python Indentation
4. What are Built-in data types in Python?
The following are the standard or built-in data types in Python:
Numeric: The numeric data type in Python represents the data that
has a numeric value. A numeric value can be an integer, a floating
number, a Boolean, or even a complex number.
Sequence Type: The sequence Data Type in Python is the ordered
collection of similar or different data types. There are several
sequence types in Python:
Python String
Python List
Python Tuple
Python range
Mapping Types: In Python, hashable data can be mapped to random
objects using a mapping object. There is currently only one common
mapping type, the dictionary and mapping objects are mutable.
Python Dictionary
Set Types: In Python, a Set is an unordered collection of data types
that is iterable, mutable and has no duplicate elements. The order of
elements in a set is undefined though it may consist of various
elements.
5.cookies
We use Whattoisensure
the you
difference
have the bestbetween a Mutable
browsing experience datatype
on our website. By and
using an
our site, you
acknowledge that you have read and understood our Cookie Policy & Privacy Policy Cookies are not
Immutable data type?
collected in the GeeksforGeeks mobile applications.
Mutable data types can be edited i.e., they can change at runtime. Eg
– List, Dictionary, etc.
Immutable data types can not be edited i.e., they can not change at
runtime. Eg – String, Tuple, etc.
6. What is a Variable Scope in Python?
The location where we can find a variable and also access it if required
is called the scope of a variable.
Python Local variable: Local variables are those that are initialized
within a function and are unique to that function. It cannot be
accessed outside of the function.
Python Global variables: Global variables are the ones that are
defined and declared outside any function and are not specified to
any function.
Module-level scope: It refers to the global objects of the current
module accessible in the program.
Outermost scope: It refers to any built-in names that the program
can call. The name referenced is located last among the objects in
this scope.
7. How do you floor a number in Python?
To floor a number in Python, you can use the math.floor() function,
which returns the largest integer less than or equal to the given number.
floor() method in Python returns the floor of x i.e., the largest integer
not greater than x.
Also, The method ceil(x) in Python returns a ceiling value of x i.e., the
smallest integer greater than or equal to x.
import math
We use ncookies
= 3.7to ensure you have the best browsing experience on our website. By using our site, you
F_num = math.floor(n)
acknowledge that you have read and understood our Cookie Policy & Privacy Policy Cookies are not
print(F_num) collected in the GeeksforGeeks mobile applications.
Output
8. What is the difference between / and // in Python?
/ represents precise division (result is a floating point number) whereas
// represents floor division (result is an integer). For Example:
5//2 = 2
5/2 = 2.5
9. Difference between for loop and while loop in Python
The “for” Loop is generally used to iterate through the elements of
various collection types such as List, Tuple, Set and Dictionary.
Developers use a “for” loop where they have both the conditions start
and the end. Whereas, the “while” loop is the actual looping feature that
is used in any other programming language. Programmers use a
Python while loop where they just have the end conditions.
10. Can we Pass a function as an argument in Python?
Yes, Several arguments can be passed to a function, including objects,
variables (of the same or distinct data types) and functions. Functions
can be passed as parameters to other functions because they are
objects. Higher-order functions are functions that can take other
functions as arguments.
We use
11.cookies
What to ensure you have
is a pass inthe best browsing experience on our website. By using our site, you
Python?
acknowledge that you have read and understood our Cookie Policy & Privacy Policy Cookies are not
collected in the GeeksforGeeks mobile applications.
Pass statement in Python is a null operation or a placeholder. It is used
when a statement is syntactically required but we don’t want to execute
any code. It does nothing but allows us to maintain the structure of our
program.
Example Use of Pass Keyword in a Function:
Pass keyword in a function is used when we define a function but don’t
want to implement its logic immediately. It allows the function to be
syntactically valid, even though it doesn’t perform any actions yet.
def fun():
pass # Placeholder, no functionality yet
# Call the function
fun()
12. What is a break, continue and pass in Python?
break statement is used to terminate the loop or statement in which
it is present. After that, the control will pass to the statements that
are present after the break statement, if available.
Continue is also a loop control statement just like the break
statement. continue statement is opposite to that of the break
statement, instead of terminating the loop, it forces to execute the
next iteration of the loop.
Pass means performing no operation or in other words, it is a
placeholder in the compound statement, where there should be a
blank left and nothing has to be written there.
13. How are arguments passed by value or by reference in
Python?
Python’s argument-passing model is neither “Pass by Value” nor “Pass
by Reference” but it is “Pass by Object Reference”.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
Depending
acknowledge onhave
that you theread
typeandof object our
understood youCookie
passPolicy
in the function,
& Privacy the function
Policy Cookies are not
behaves differently. Immutable
collected objects
in the GeeksforGeeks show
mobile “pass by value” whereas
applications.
mutable objects show “pass by reference”.
You can check the difference between pass-by-value and pass-by-
reference in the example below:
def call_by_value(x):
x = x * 2
print("in function value updated to", x)
return
def call_by_reference(list):
list.append("D")
print("in function list updated to", list)
return
my_list = ["E"]
num = 6
print("number before=", num)
call_by_value(num)
print("after function num value=", num)
print("list before",my_list)
call_by_reference(my_list)
print("after function list is ",my_list)
Output
number before= 6
in function value updated to 12
after function num value= 6
list before ['E']
in function list updated to ['E', 'D']
after function list is ['E', 'D']
14. What is a lambda function?
A lambda function is an anonymous function. This function can have
any number of parameters but, can have just one statement.
In the example, we defined a lambda function(upper) to convert a string
to its upper case using upper().
s1 = 'GeeksforGeeks'
s2 = lambda func: func.upper()
We use print(s2(s1))
cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our Cookie Policy & Privacy Policy Cookies are not
collected in the GeeksforGeeks mobile applications.
Output
GEEKSFORGEEKS
15. How is a dictionary different from a list?
A list is an ordered collection of items accessed by their index, while a
dictionary is an unordered collection of key-value pairs accessed using
unique keys. Lists are ideal for sequential data, whereas dictionaries
are better for associative data. For example, a list can store [10, 20, 30],
whereas a dictionary can store {“a”: 10, “b”: 20, “c”: 30}.
16. What is List Comprehension? Give an Example.
List comprehension is a way to create lists using a concise syntax. It
allows us to generate a new list by applying an expression to each item
in an existing iterable (such as a list or range). This helps us to write
cleaner, more readable code compared to traditional looping
techniques.
For example, if we have a list of integers and want to create a new list
containing the square of each element, we can easily achieve this using
list comprehension.
a = [2,3,4,5]
res = [val ** 2 for val in a]
print(res)
Output
[4, 9, 16, 25]
17. What are *args and **kwargs?
*args: The special syntax *args in function definitions is used to pass a
variable number of arguments to a function. Python program to
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
illustrate
acknowledge *args
that forread
you have a variable number
and understood of arguments:
our Cookie Policy & Privacy Policy Cookies are not
collected in the GeeksforGeeks mobile applications.
def myFun(*argv):
for arg in argv:
print(arg)
myFun('Hello', 'Welcome', 'to', 'GeeksforGeeks')
Output
Hello
Welcome
to
GeeksforGeeks
**kwargs: The special syntax **kwargs in function definitions is used to
pass a variable length argument list. We use the name kwargs with the
double star **.
def fun(**kwargs):
for k, val in kwargs.items():
print("%s == %s" % (k, val))
# Driver code
fun(s1='Geeks', s2='for', s3='Geeks')
Output
s1 == Geeks
s2 == for
s3 == Geeks
18. What is the difference between a Set and Dictionary?
A Python Set is an unordered collection data type that is iterable,
mutable and has no duplicate elements. Python’s set class represents
the mathematical notion of a set.
Syntax: Defined using curly braces {} or the set() function.
my_set = {1, 2, 3}
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our Cookie Policy & Privacy Policy Cookies are not
collected in the GeeksforGeeks mobile applications.
Dictionary in Python is an ordered (since Py 3.7) [unordered (Py 3.6 &
prior)] collection of data values, used to store data values like a map,
which, unlike other Data Types that hold only a single value as an
element, Dictionary holds key:value pair. Key-value is provided in the
dictionary to make it more optimized.
Syntax: Defined using curly braces {} with key-value pairs.
my_dict = {“a”: 1, “b”: 2, “c”: 3}
19. How can you concatenate two lists in Python?
We can concatenate two lists in Python using the +operator or the
extend() method.
1. Using the + operator:
This creates a new list by joining two lists together.
list1 = [1, 2, 3]
list2 = [4, 5, 6]
result = list1 + list2
print(result)
Output
[1, 2, 3, 4, 5, 6]
2. Using the extend() method:
This adds all the elements of the second list to the first list in-place.
list1 = [1, 2, 3]
list2 = [4, 5, 6]
list1.extend(list2)
print(list1)
Output
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our Cookie Policy & Privacy Policy Cookies are not
[1, 2, 3, 4,collected
5, 6]in the GeeksforGeeks mobile applications.
20. What is docstring in Python?
Python documentation strings (or docstrings) provide a convenient way
of associating documentation with Python modules, functions, classes
and methods.
Declaring Docstrings: The docstrings are declared using ”’triple
single quotes”’ or “””triple double quotes””” just below the class,
method, or function declaration. All functions should have a
docstring.
Accessing Docstrings: The docstrings can be accessed using the
__doc__ method of the object or using the help function.
21. How is Exceptional handling done in Python?
There are 3 main keywords i.e. try, except and finally which are used to
catch exceptions and handle the recovering mechanism accordingly.
Try is the block of a code that is monitored for errors. Except block gets
executed when an error occurs.
The beauty of the final block is to execute the code after trying for an
error. This block gets executed irrespective of whether an error
occurred or not. Finally, block is used to do the required cleanup
activities of objects/variables.
Example: Trying to divide a number by zero will cause an exception.
n = 10
try:
res = n / 0 # This will raise a ZeroDivisionError
except ZeroDivisionError:
print("Can't be divided by zero!")
Output
Can't be divided by zero!
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our Cookie Policy & Privacy Policy Cookies are not
Explanation: Incollected
this example, dividing number
in the GeeksforGeeks by 0 raises
mobile applications.
a ZeroDivisionError. The try block contains the code that might cause
an exception and the except block handles the exception, printing an
error message instead of stopping the program.
1/3
22. What is the difference between Python Arrays and Lists?
Arrays (when talking about the array module in Python) are specifically
used to store a collection of numeric elements that are all of the same
type. This makes them more efficient for storing large amounts of data
and performing numerical computations where the type consistency is
maintained.
Syntax: Need to import the array module to use arrays.
Example:
from array import array
arr = array('i', [1, 2, 3, 4]) # Array of integers
Lists are more flexible than arrays in that they can hold elements of
different types (integers, strings, objects, etc.). They come built-in with
Python and do not require importing any additional modules.
Lists support a variety of operations that can modify the list.
Example:
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge
lst = that
[1,you have read3.14,
'hello', and understood
[1, 2, our Cookie Policy & Privacy Policy Cookies are not
3]]
collected in the GeeksforGeeks mobile applications.
read more about Difference between List and Array in Python
23. What are Modules and Packages in Python?
A module is a single file that contains Python code (functions,
variables, classes) which can be reused in other programs. You can
think of it as a code library. For example: math is a built-in module that
provides math functions like sqrt(), pi, etc.
import math
print(math.sqrt(16))
package is a collection of related modules stored in a directory. It helps
in organizing and grouping modules together for easier management.
For example: The numpy package contains multiple modules for
numerical operations.
To create a package, the directory must contain a special file named
__init__.py.
Intermediate Python Interview Questions
24. What is the difference between xrange and range functions?
range() and xrange() are two functions that could be used to iterate a
certain number of times in for loops in Python.
In Python 3, there is no xrange, but the range function behaves like
xrange.
In Python 2
range() – This returns a range object, which is an
immutable sequence type that generates the numbers on
demand.
xrange() – This function returns the generator object that
can be used to display numbers only by looping. The only
We use cookies to ensure you haverange
particular the bestis
browsing experience
displayed on our website.
on demand and By using our
hence site, you
called
acknowledge that you have read and understood our Cookie Policy & Privacy Policy Cookies are not
lazycollected
evaluation.
in the GeeksforGeeks mobile applications.
25. What is Dictionary Comprehension? Give an Example
Dictionary Comprehension is a syntax construction to ease the creation
of a dictionary based on the existing iterable.
# Python code to demonstrate dictionary
# comprehension
# Lists to represent keys and values
keys = ['a','b','c','d','e']
values = [1,2,3,4,5]
# but this line shows dict comprehension here
myDict = { k:v for (k,v) in zip(keys, values)}
# We can use below too
# myDict = dict(zip(keys, values))
print (myDict)
Output
{'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
26. Is Tuple Comprehension possible in Python? If yes, how and if
not why?
Tuple comprehensions are not directly supported, Python’s existing
features like generator expressions and the tuple() function provide
flexible alternatives for creating tuples from iterable data.
(i for i in (1, 2, 3))
Tuple comprehension is not possible in Python because it will end up in
a generator, not a tuple comprehension.
27. Differentiate between List and Tuple?
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
Let’s analyze
acknowledge that you the
havedifferences between
read and understood ListPolicy
our Cookie and & Tuple : Policy Cookies are not
Privacy
collected in the GeeksforGeeks mobile applications.
List
Lists are Mutable datatype.
Lists consume more memory
The list is better for performing operations, such as insertion and
deletion.
The implication of iterations is Time-consuming
Tuple
Tuples are Immutable datatype.
Tuple consumes less memory as compared to the list
A Tuple data type is appropriate for accessing the elements
The implication of iterations is comparatively Faster
28. What is the difference between a shallow copy and a deep
copy?
Below is the tabular Difference between the Shallow Copy and Deep
Copy:
Shallow Copy Deep Copy
Shallow Copy stores the
Deep copy stores copies of the
references of objects to the
object’s value.
original memory address.
Shallow Copy reflects changes Deep copy doesn’t reflect changes
made to the new/copied object in made to the new/copied object in
the original object. the original object.
Shallow Copy stores the copy of Deep copy stores the copy of the
the original object and points the original object and recursively
references to the objects. copies the objects as well.
A shallow copy is faster. Deep copy is comparatively slower.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our Cookie Policy & Privacy Policy Cookies are not
collected in the GeeksforGeeks mobile applications.
29. Which sorting technique is used by sort() and sorted()
functions of python?
Python uses the Tim Sort algorithm for sorting. It’s a stable sorting
whose worst case is O(N log N). It’s a hybrid sorting algorithm, derived
from merge sort and insertion sort, designed to perform well on many
kinds of real-world data.
30. What are Decorators?
Decorators are a powerful and flexible way to modify or extend the
behavior of functions or methods, without changing their actual code. A
decorator is essentially a function that takes another function as an
argument and returns a new function with enhanced functionality.
Decorators are often used in scenarios such as logging, authentication
and memorization, allowing us to add additional functionality to
existing functions or methods in a clean, reusable way.
31. How do you debug a Python program?
1. Using pdb (Python Debugger):
pdb is a built-in module that allows you to set breakpoints and step
through the code line by line. You can start the debugger by adding
import pdb; pdb.set_trace() in your code where you want to begin
debugging.
import pdb
x = 5
pdb.set_trace() # Debugger starts here
print(x)
Output
> /home/repl/02c07243-5df9-4fb0-a2cd-
We use54fe6d597c80/main.py(4)<module>()
cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our Cookie Policy & Privacy Policy Cookies are not
-> print(x)
collected in the GeeksforGeeks mobile applications.
(Pdb)
2. Using logging Module:
For more advanced debugging, the logging module provides a flexible
way to log messages with different severity levels (INFO, DEBUG,
WARNING, ERROR, CRITICAL).
import logging
logging.basicConfig(level=logging.DEBUG)
logging.debug("This is a debug message")
Output
DEBUG:root:This is a debug message
32. What are Iterators in Python?
In Python, iterators are used to iterate a group of elements, containers
like a list. Iterators are collections of items and they can be a list,
tuples, or a dictionary. Python iterator implements __itr__ and the next()
method to iterate the stored elements. We generally use loops to iterate
over the collections (list, tuple) in Python.
33. What are Generators in Python?
In Python, the generator is a way that specifies how to implement
iterators. It is a normal function except that it yields expression in the
function. It does not implement __itr__ and __next__ method and
reduces other overheads as well.
If a function contains at least a yield statement, it becomes a generator.
The yield keyword pauses the current execution by saving its states and
then resumes from the same when required.
34. Does Python supports multiple Inheritance?
When a class is derived from more than one base class it is called
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
multiplethat
acknowledge Inheritance.
you have readThe derived class
and understood inherits
our Cookie Policy &all the features
Privacy of the
Policy Cookies are not
collected in the GeeksforGeeks mobile applications.
base case.
Multiple Inheritance
Python does support multiple inheritances, unlike Java.
35. What is Polymorphism in Python?
Polymorphism means the ability to take multiple forms. Polymorphism
allows different classes to be treated as if they are instances of the
same class through a common interface. This means that a method in
a parent class can be overridden by a method with the same name in a
child class, but the child class can provide its own specific
implementation. This allows the same method to operate differently
depending on the object that invokes it. Polymorphism is about
overriding, not overloading; it enables methods to operate on objects of
different classes, which can have their own attributes and methods,
providing flexibility and reusability in the code.
36. Define encapsulation in Python?
Encapsulation is the process of hiding the internal state of an object
and requiring all interactions to be performed through an object’s
methods. This approach:
Provides better control over data.
Prevents accidental modification of data.
Promotes
We use cookies modular
to ensure you have programming.
the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our Cookie Policy & Privacy Policy Cookies are not
collected in the GeeksforGeeks mobile applications.
Python achieves encapsulation
through public, protected and private attributes.
Encapsulation in Python
37. How do you do data abstraction in Python?
Data Abstraction is providing only the required details and hides the
implementation from the world. The focus is on exposing only the
essential features and hiding the complex implementation behind an
interface. It can be achieved in Python by using interfaces and abstract
classes.
38. How is memory management done in Python?
Python uses its private heap space to manage the memory. Basically,
all the objects and data structures are stored in the private heap space.
Even the programmer can not access this private space as the
interpreter takes care of this space. Python also has an inbuilt garbage
collector, which recycles all the unused memory and frees the memory
and makes it available to the heap space.
39. How to delete a file using Python?
We can delete a file using Python by following approaches:
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
1. Python Delete File using os. remove
acknowledge that you have read and understood our Cookie Policy & Privacy Policy Cookies are not
2. Delete file incollected
Pythonin using the send2trash
the GeeksforGeeks module
mobile applications.
3. Python Delete File using os.rmdir
40. What is slicing in Python?
Python Slicing is a string operation for extracting a part of the string, or
some part of a list. With this operator, one can specify where to start
the slicing, where to end and specify the step. List slicing returns a new
list from the existing list.
Syntax:
substring = s[start : end : step]
41. What is a namespace in Python?
A namespace in Python refers to a container where names (variables,
functions, objects) are mapped to objects. In simple terms, a
namespace is a space where names are defined and stored and it helps
avoid naming conflicts by ensuring that names are unique within a
given scope.
Types of namespaces
Types of Namespaces:
1. Built-in Namespace: Contains all the built-in functions and
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
exceptions,
acknowledge likeread
that you have , int(), our
and understood
print() etc.Cookie
These are& Privacy
Policy available
PolicyinCookies
every are not
collected in the GeeksforGeeks mobile applications.
Python program.
2. Global Namespace: Contains names from all the objects, functions
and variables in the program at the top level.
3. Local Namespace: Refers to names inside a function or method.
Each function call creates a new local namespace.
Python Interview
Advanced Python Interview Questions & Answers
42. What is PIP?
PIP is an acronym for Python Installer Package which provides a
seamless interface to install various Python modules. It is a command-
line tool that can search for packages over the internet and install them
without any user interaction.
43. What is a zip function?
Python zip() function returns a zip object, which maps a similar index of
multiple containers. It takes an iterable, converts it into an iterator and
aggregates the elements based on iterables passed. It returns an
iterator of tuples.
Syntax:
zip(*iterables)
44.
We use What
cookies are Pickling
to ensure you have theand
bestUnpickling?
browsing experience on our website. By using our site, you
acknowledge that you have read and understood our Cookie Policy & Privacy Policy Cookies are not
collected in the GeeksforGeeks mobile applications.
Pickling: The pickle module converts any Python object into a byte
stream (not a string representation). This byte stream can then be
stored in a file, sent over a network, or saved for later use. The
function used for pickling is pickle.dump().
Unpickling: The process of retrieving the original Python object from
the byte stream (saved during pickling) is called unpickling. The
function used for unpickling is pickle.load().
45. What is the difference between @classmethod, @staticmethod and
instance methods in Python?
1. Instance Method operates on an instance of the class and has
access to instance attributes and takes self as the first parameter.
Example:
def method(self):
2. Class Method directly operates on the class itself and not on
instance, it takes cls as the first parameter and defined with
@classmethod.
Example: @classmethod def method(cls):
3. Static Method does not operate on an instance or the class and
takes no self or cls as an argument and is defined with @staticmethod.
Example: @staticmethod def method(): align it and dont bolod
anything and not bullet points
46. What is __init__() in Python and how does self play a role in
it?
__init__() method in Python is equivalent to constructors in OOP
terminology.
We use It you
cookies to ensure is a reserved
have method
the best browsing in Python
experience on our classes
website. By and
using is
our called
site, you
acknowledge that you have read and understood our Cookie Policy & Privacy Policy Cookies are not
automatically whenever a new object is instantiated. This method is
collected in the GeeksforGeeks mobile applications.
used to initialize the object’s attributes with values. While __init__()
initializes the object, it does not allocate memory. Memory allocation
for a new object is handled by the __new__() method, which is called
before __init__(). The self parameter in __init__() refers to the
instance of the class being created as it allows access to the instance’s
attributes and methods. self must be explicitly declared as the first
parameter in all instance methods, including __init__().
class MyClass:
def __init__(self, value):
self.value = value # Initialize object attribute
def display(self):
print(f"Value: {self.value}")
obj = MyClass(10)
obj.display()
Output
Value: 10
47. Write a code to display the current time?
import time
currenttime= time.localtime(time.time())
print ("Current time is", currenttime)
48. What are Access Specifiers in Python?
Python uses the ‘_’ symbol to determine the access control for a
specific data member or a member function of a class. A Class in
Python has three types of Python access modifiers:
Public Access Modifier: The members of a class that are declared
public are easily accessible from any part of the program. All data
members and member functions of a class are public by default.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
Protected Access Modifier: The members of a class that are
acknowledge that you have read and understood our Cookie Policy & Privacy Policy Cookies are not
declared protected are
collected in theonly accessible
GeeksforGeeks toapplications.
mobile a class derived from it. All
data members of a class are declared protected by adding a single
underscore ‘_’ symbol before the data members of that class.
Private Access Modifier: The members of a class that are declared
private are accessible within the class only, the private access
modifier is the most secure access modifier. Data members of a
class are declared private by adding a double underscore ‘__’ symbol
before the data member of that class.
49. What are unit tests in Python?
Unit Testing is the first level of software testing where the smallest
testable parts of the software are tested. This is used to validate that
each unit of the software performs as designed. The unit test
framework is Python’s xUnit style framework. The White Box Testing
method is used for Unit testing.
50. Python Global Interpreter Lock (GIL)?
Python Global Interpreter Lock (GIL) is a type of process lock that is
used by Python whenever it deals with processes. Generally, Python
only uses only one thread to execute the set of written statements. The
performance of the single-threaded process and the multi-threaded
process will be the same in Python and this is because of GIL in
Python. We can not achieve multithreading in Python because we have
a global interpreter lock that restricts the threads and works as a single
thread.
51. What are Function Annotations in Python?
Function Annotation is a feature that allows you to add metadata to
function parameters and return values. This way you can specify the
input type of the function parameters and the return type of the value
the function returns.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our Cookie Policy & Privacy Policy Cookies are not
Function annotations are arbitrary Python expressions that are
collected in the GeeksforGeeks mobile applications.
associated with various parts of functions. These expressions are
evaluated at compile time and have no life in Python’s runtime
environment. Python does not attach any meaning to these
annotations. They take life when interpreted by third-party libraries, for
example, mypy.
52. What are Exception Groups in Python?
The latest feature of Python 3.11, Exception Groups. The
ExceptionGroup can be handled using a new except* syntax. The *
symbol indicates that multiple exceptions can be handled by each
except* clause.
ExceptionGroup is a collection/group of different kinds of Exception.
Without creating Multiple Exceptions we can group together different
Exceptions which we can later fetch one by one whenever necessary,
the order in which the Exceptions are stored in the Exception Group
doesn’t matter while calling them.
try:
raise ExceptionGroup('Example ExceptionGroup', (
TypeError('Example TypeError'),
ValueError('Example ValueError'),
KeyError('Example KeyError'),
AttributeError('Example AttributeError')
))
except* TypeError:
...
except* ValueError as e:
...
except* (KeyError, AttributeError) as e:
...
53. What is Python Switch Statement?
From version 3.10 upward, Python has implemented a switch case
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
feature that
acknowledge called “structural
you have patternourmatching”.
read and understood Cookie Policy You can
& Privacy implement
Policy Cookies arethis
not
collected in the GeeksforGeeks mobile applications.
feature with the match and case keywords. Note that the underscore
symbol is what you use to define a default case for the switch
statement in Python.
Note: Before Python 3.10 Python doesn’t support match Statements.
match term:
case pattern-1:
action-1
case pattern-2:
action-2
case pattern-3:
action-3
case _:
action-default
54. What is Walrus Operator?
Walrus Operator allows you to assign a value to a variable within an
expression. This can be useful when you need to use a value multiple
times in a loop, but don’t want to repeat the calculation.
Walrus Operator is represented by the `:=` syntax and can be used in a
variety of contexts including while loops and if statements.
Note: Python versions before 3.8 doesn’t support Walrus Operator.
numbers = [1, 2, 3, 4, 5]
while (n := len(numbers)) > 0:
print(numbers.pop())
Output
5
4
3
2
1
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
Get 90%
acknowledge thatfee read on
refund
you have andcompleting
understood our 90%
Cookiecourse
Policy & in 90 days!
Privacy Take the
Policy Cookies are not
Three 90 Challengecollectedtoday.
in the GeeksforGeeks mobile applications.
Step into the Three 90 Challenge – 90 days to push limits, break
barriers, and become the best version of yourself! Don't miss your
chance to upskill and get 90% refund. What more motivation do you
need? Start the challenge right away!
Comment More info Next Article
Java Interview Questions and
Placement Training Program
Answers
Similar Reads
Top 50 Blockchain Interview Questions and Answers
Blockchain is one of the most trending technologies out there in the tech
world. It is basically concerned with a distributed database that maintai…
15+ min read
Top 50 Ethical Hacking Interview Questions and Answers
In today’s digital age, cybersecurity has become a top priority for
organizations worldwide, creating a high demand for skilled professiona…
15+ min read
Top 40 Flask Interview Questions and Answers
Flask is a popular Python web framework used to build web applications.
If you're preparing for a Flask development position, it's important to be…
15 min read
Top 50 Penetration Testing Interview Questions and Answers
Penetration testing stands for a process where the security of a computer
system is tested by trying to gain access to its internal systems. In order…
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
15+ min read
acknowledge that you have read and understood our Cookie Policy & Privacy Policy Cookies are not
collected in the GeeksforGeeks mobile applications.
Top 25 Android Interview Questions and Answers For…
The need for new technologies and their developers is increasing as the
world is dynamically transforming digitally. Everyone nowadays relies on…
15+ min read
Top C++ Exception Handling Interview Questions and Answers
Exception Handling is one of the most important topics from the C++
Interview perspective. Exception handling is an effective means to handl…
8 min read
Top C++ STL Interview Questions and Answers
The Standard Template Library (STL) is a set of C++ template classes
that are used to implement widely popular algorithms and data structur…
15+ min read
Top 10 Most Commonly Asked Web3 Interview Questions and…
Web3 (also known as Web 3.0) is definitely the latest technology that the
world is currently basking on and slowly small and big companies are…
7 min read
Top 10 Traditional HR Interview Questions and Answers
Preparing for an HR interview can be one of the most critical steps in
securing your next job. It’s your chance to make a lasting impression, as…
12 min read
20 Top Situational Interview Questions and Answers
Situational interview questions are a great way for employers to evaluate
how you handle real-life work scenarios and challenges. These question…
8 min read
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our Cookie Policy & Privacy Policy Cookies are not
collected in the GeeksforGeeks mobile applications.
Corporate & Communications
Address:
A-143, 7th Floor, Sovereign Corporate
Tower, Sector- 136, Noida, Uttar
Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante
Apartment, Sector 137, Noida,
Gautam Buddh Nagar, Uttar Pradesh,
201305
Advertise with us
Company Explore
About Us Job-A-Thon Hiring Challenge
Legal Hack-A-Thon
Privacy Policy GfG Weekly Contest
Careers Offline Classes (Delhi/NCR)
In Media DSA in JAVA/C++
Contact Us Master System Design
GfG Corporate Solution Master CP
Placement Training Program GeeksforGeeks Videos
Geeks Community
Languages DSA
Python Data Structures
Java Algorithms
C++ DSA for Beginners
PHP Basic DSA Problems
GoLang DSA Roadmap
SQL DSA Interview Questions
R Language Competitive Programming
Android Tutorial
Data Science & ML Web Technologies
Data Science With Python HTML
We use cookiesData Science
to ensure Forhave
you Beginner
the best browsing experience on our website.CSS
By using our site, you
Machine Learning JavaScript
acknowledge that you have read and understood our Cookie Policy & Privacy Policy Cookies are not
MLcollected
Maths in the GeeksforGeeks mobile applications. TypeScript
Data Visualisation ReactJS
Pandas NextJS
NumPy NodeJs
NLP Bootstrap
Deep Learning Tailwind CSS
Python Tutorial Computer Science
Python Programming Examples GATE CS Notes
Django Tutorial Operating Systems
Python Projects Computer Network
Python Tkinter Database Management System
Web Scraping Software Engineering
OpenCV Tutorial Digital Logic Design
Python Interview Question Engineering Maths
DevOps System Design
Git High Level Design
AWS Low Level Design
Docker UML Diagrams
Kubernetes Interview Guide
Azure Design Patterns
GCP OOAD
DevOps Roadmap System Design Bootcamp
Interview Questions
School Subjects Software and Tools
Mathematics AI Tools Directory
Physics Marketing Tools Directory
Chemistry Accounting Software Directory
Biology HR Management Tools
Social Science Editing Software Directory
English Grammar Microsoft Products and Apps
Figma Tutorial
Databases Preparation Corner
SQL Company-Wise Recruitment Process
MYSQL Resume Templates
PostgreSQL Aptitude Preparation
PL/SQL Puzzles
MongoDB Company-Wise Preparation
Companies
Colleges
Competitive Exams More Tutorials
JEE Advanced Software Development
UGC NET Software Testing
We use cookies to ensureUPSC Product Management
you have the best browsing experience on our website. By using our site, you
acknowledge that you SSC
haveCGL Project
read and understood our Cookie Policy & Privacy Management
Policy Cookies are not
collected
SBI PO in the GeeksforGeeks mobile applications. Linux
SBI Clerk Excel
IBPS PO All Cheat Sheets
IBPS Clerk Recent Articles
Free Online Tools Write & Earn
Typing Test Write an Article
Image Editor Improve an Article
Code Formatters Pick Topics to Write
Code Converters Share your Experiences
Currency Converter Internships
Random Number Generator
Random Password Generator
DSA/Placements Development/Testing
DSA - Self Paced Course JavaScript Full Course
DSA in JavaScript - Self Paced Course React JS Course
DSA in Python - Self Paced React Native Course
C Programming Course Online - Learn C with Data Django Web Development Course
Structures Complete Bootstrap Course
Complete Interview Preparation Full Stack Development - [LIVE]
Master Competitive Programming JAVA Backend Development - [LIVE]
Core CS Subject for Interview Preparation Complete Software Testing Course [LIVE]
Mastering System Design: LLD to HLD Android Mastery with Kotlin [LIVE]
Tech Interview 101 - From DSA to System Design [LIVE]
DSA to Development [HYBRID]
Placement Preparation Crash Course [LIVE]
Machine Learning/Data Science Programming Languages
Complete Machine Learning & Data Science Program - C Programming with Data Structures
[LIVE] C++ Programming Course
Data Analytics Training using Excel, SQL, Python & Java Programming Course
PowerBI - [LIVE] Python Full Course
Data Science Training Program - [LIVE]
Mastering Generative AI and ChatGPT
Data Science Course with IBM Certification
Clouds/Devops GATE 2026
DevOps Engineering GATE CS Rank Booster
AWS Solutions Architect Certification GATE DA Rank Booster
Salesforce Certified Administrator Course GATE CS & IT Course - 2026
GATE DA Course 2026
GATE Rank Predictor
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our Cookie Policy & Privacy Policy Cookies are not
collected in the GeeksforGeeks mobile applications.