GeezerVisonThe World Wide Web, restored to 800 pixels of glory. | ||||||||||
| Home|About|Gaming cabinet|Archives|How it works|Starter sites | ||||||||||
GeezerVison is showing www.geeksforgeeks.org — Top 50+ Python Interview Questions and Answers (2025) - GeeksforGeeks Python Interview Questions and AnswersLast Updated : 11 Jul, 2026 Python is widely used by leading companies such as Intel, IBM, NASA, Pixar, Netflix, Meta, JPMorgan Chase and Spotify due to its simplicity and rich ecosystem of libraries. Mastering key Python interview questions is essential for succeeding in coding assessments and technical interviews for Python developer roles. 1. Is Python a compiled language or an interpreted language?Python is considered both a compiled and an interpreted language. First, Python source code (.py files) is compiled into bytecode (.pyc files). Then, the Python Virtual Machine (PVM) interprets and executes this bytecode line by line.
Therefore, Python combines features of both compiled and interpreted languages. 2. 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. ![]() 3. What is a dynamically typed language?A dynamically typed language is a programming language in which the data type of a variable is determined at runtime. In Python, you do not need to declare the data type of a variable explicitly. Instead, Python automatically assigns the appropriate type based on the value stored in the variable.
Here, the variable x initially stores an integer and is later reassigned to a string. Python automatically updates the variable's type at runtime. 4. What are Built-in data types in Python?The following are the standard or built-in data types in Python: ![]()
5. What is the difference between a Mutable datatype and an Immutable data type?
Explanation: In the first example, the list a is modified directly by adding a new element. In the second example, strings are immutable, so concatenating " World" creates a new string object and assigns it back to s. 6. What is the difference between == and is in Python?Both == and is are comparison operators, but they compare different things.
Output True False True 7. 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:
Output 2 2.5 8. 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.
Output 3 9. What is the difference between a Set and Dictionary?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. Defined using curly braces {} or the set() function.
Dictionary is a collection of key-value pairs used to store and retrieve data using unique keys. Dictionaries preserve insertion order. Defined using curly braces {} with key-value pairs.
10. How is a dictionary different from a list?A list is an ordered collection of items that are accessed using their index position, whereas a dictionary is an ordered collection of key-value pairs that are accessed using unique keys. Lists are suitable for storing sequential data, while dictionaries are ideal for storing data associated with meaningful keys.
Output 20 Emma 11. 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.
Output array('i', [1, 2, 3, 4])
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.
Output [1, 'hello', 3.14, [1, 2, 3]]
12. Difference between for loop and while loop in Python
Output 0 1 2 3 4 0 1 2 3 4 13. What is a break, continue and pass in Python?
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(). ![]()
Output GEEKSFORGEEKS 15. What are map(), filter(), and reduce() in Python?These functions are used for functional programming:
Output [2, 4, 6, 8] [2, 4] 10 16. 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.
Output 8 The add function is passed as an argument to apply_func, which applies it to 3 and 5. 17. What are *args and **kwargs?*args: used to pass a variable number of arguments to a function. Python program to illustrate *args for a variable number of arguments.
Output Hello Welcome to GeeksforGeeks **kwargs: used to accept a variable number of keyword arguments. These arguments are collected into a dictionary, where the keys are the argument names and the values are the corresponding values.
Output s1 == Geeks s2 == for s3 == Geeks 18. How are arguments passed by value or by reference in Python?Python uses Pass by Object Reference (also called Call by Object Sharing) to pass arguments to functions. Instead of passing values or references directly, Python passes a reference to the object. Whether the original object changes depends on whether it is mutable or immutable.
Output Updated value after call_by_val: 12 Updated list after call_by_ref: ['E', 'D'] 19. 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.
20. What is the LEGB rule in Python?Python follows the LEGB rule to resolve variable names. LEGB stands for:
Python searches for a variable in this order until it is found.
Output Local 21. What are the global and nonlocal keywords in Python?Both keywords allow modifying variables outside the current function.
Output 1 Example of nonlocal:
Output 15 22. What is docstring in Python?Python documentation strings (or docstrings) provide a convenient way of associating documentation with Python modules, functions, classes and methods.
Output Return the sum of two numbers.
Help on function add in module __main__:
add(a, b)
Return the sum of two numbers.Explanation: In this example, the function add() includes a docstring that describes its purpose. The docstring can be viewed directly using add.__doc__ or through the built-in help() function. 23. How can you concatenate two lists in Python?We can concatenate two lists in Python using the +operator or the extend() method. 1. + operator: This creates a new list by joining two lists together.
Output [1, 2, 3, 4, 5, 6] 2. extend() : This adds all the elements of the second list to the first list in-place.
Output [1, 2, 3, 4, 5, 6] 24. What is the difference between append() and extend()?Both methods add elements to a list:
Output [1, 2, [3, 4]] [1, 2, 3, 4] 25. What is the difference between remove(), pop(), and del?All three remove elements from a list but work differently:
Output [30] 26. 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.
Output [4, 9, 16, 25] 27. How is Exceptional handling done in Python?Exception handling in Python is used to manage runtime errors gracefully without stopping the program abruptly. Python provides three main keywords for handling exceptions:
Example: Trying to divide a number by zero will cause an exception.
Output Can't be divided by zero! Execution completed. Explanation: In this example, dividing number by 0 raises 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. 28. 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.
Output 4.0 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. 29. What is the purpose of if __name__ == "__main__" in Python?The if __name__ == "__main__" statement ensures that a block of code runs only when the file is executed directly, not when it is imported as a module.
Output Hello Intermediate Python Interview Questions30. What is slicing in Python?Slicing is a technique used to extract a portion of a sequence such as a string, list, tuple or range. It allows to specify a starting index, an ending index and an optional step value.
Output [20, 30, 40] 31. Differentiate between List and Tuple?Let’s analyze the differences between List and Tuple: List
Tuple
32. What is Dictionary Comprehension? Give an ExampleDictionary Comprehension is a concise way to create dictionaries from existing iterables. It allows to generate key-value pairs in a single line of code, making the code more readable and efficient.
Output {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
33. 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.
Explanation:
34. What is the difference between a shallow copy and a deep copy?Below is the tabular difference between the Shallow Copy and Deep Copy:
35. What are Iterators in Python?Iterators are used to iterate a group of elements, containers like a list. Iterators work on iterable objects such as lists, tuples and dictionaries. Python iterator implements __iter__() and the next() methods to iterate the stored elements. We generally use loops to iterate over the collections (list, tuple) in Python.
Output G F G 36. What are Magic (Dunder) Methods in Python?Magic methods are special methods whose names begin and end with double underscores. They allow developers to customize the behavior of objects. Common magic methods include:
Output Alice 37. What are Generators in Python?Generators are a simple and memory-efficient way to create iterators in Python. They generate values one at a time only when needed, rather than storing all values in memory at once. A function becomes a generator if it contains the yield statement. Each time yield is executed, the function returns a value and pauses its execution. When the next value is requested, execution resumes from where it left off. Generators automatically implement the __iter__() and __next__() methods, which allows them to be used directly in loops and with the next() function.
Output 1 2 3 4 5 38. 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. 39. What is the difference between sort() and sorted()?sort()
sorted()
Output [1, 2, 3] [3, 1, 2] [1, 2, 3] 40. Does Python supports multiple Inheritance?When a class is derived from more than one base class it is called multiple Inheritance. The derived class inherits all the features of the base case. ![]() Python does support multiple inheritances, unlike some programming languages that restrict multiple inheritance of classes. For example:
Output Method from class A Method from class B Explanation:
41. What is Method Resolution Order (MRO) in Python?Method Resolution Order (MRO) defines the order in which Python searches for methods in classes when multiple inheritance is used. The MRO can be viewed using the mro() method.
Output [<class '__main__.C'>, <class '__main__.B'>, <class '__main__.A'>, <class 'object'>] 42. What is the purpose of the super() function in Python?The super() function allows a child class to access methods and constructors of its parent class.
Output Animal Dog 43. What is Polymorphism in Python?Polymorphism means "many forms." It allows same method name to perform different actions depending on the object that calls it. This is achieved through method overriding, where child classes provide their own implementation of a method defined in a parent class.
Output Bark Meow Explanation:
44. 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:
Python achieves encapsulation through public, protected and private attributes. ![]() 45. How do you do data abstraction in Python?Data Abstraction means providing only the essential details while hiding the implementation. It allows users to interact with an object through a simple interface without needing to understand its internal working. It's achieved using abstract base classes provided by the abc module. These classes define abstract methods that must be implemented by derived classes. ![]()
Output 78.5 Explanation:
46. What are Decorators?Decorators is a 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. 47. What is a namespace in Python?A namespace 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:
48. 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. Python manages memory automatically using a private heap, where all objects and data structures are stored. Python interpreter handles memory allocation and deallocation and an inbuilt garbage collector reclaims memory occupied by objects that are no longer in use.
49. How to delete a file using Python?Python provides several ways to delete files, some of them are as following:
50. 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.
Output
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).
Output
51. What is the difference between xrange and range functions?range() and xrange() were both used in Python 2 to generate sequences of numbers for iteration. In Python 3, there is no xrange, but the range function behaves like xrange.
Advanced Python Interview Questions & Answers52. What is PIP?PIP stands for "Pip Installs Packages." It is Python’s standard package manager used to install, upgrade and manage third-party libraries and dependencies from the Python Package Index (PyPI).
53. What is a zip function?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.
Output [('Hiro', 88), ('Mila', 94)]
54. Write a code to display the current time?The datetime module provides the datetime.now() method, which returns the current local date and time. It is commonly used to display timestamps, log events, or retrieve the current system date and time.
Output Current time is: 2026-05-11 11:10:41.581886 55. What is __init__() in Python and how does self play a role in it?__init__() is Python's equivalent of constructors in OOP, called automatically when a new object is created. It initializes the object's attributes with values but doesn’t handle memory allocation.
Output Value: 10 56. What is the difference between __new__() and __init__()?
__new__() is called before __init__(). 57. 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:
Output Mike 101 95 Explanation:
58. What is the difference between @classmethod, @staticmethod and instance methods in Python?
Output Student Name: Kevin School: ABC School True 59. What are Pickling and Unpickling?
60. What are Exception Groups in Python?Exception Groups are a feature introduced in Python 3.11 that allow multiple exceptions to be grouped together and handled in a structured way. They are particularly useful when several operations may fail independently, such as in concurrent or asynchronous programs. ExceptionGroup class is used to combine multiple exceptions into a single object and the except* syntax is used to handle specific exception types within the group.
Output Handled TypeError Handled ValueError Handled KeyError and AttributeError 61. What is a Context Manager in Python?A context manager automatically manages resources such as files, network connections, or database connections. It is commonly used with the with statement.
Benefits:
62. 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.
Output
63. Python Global Interpreter Lock (GIL)?Global Interpreter Lock (GIL) is a mechanism used in the CPython interpreter that allows only one thread to execute Python bytecode at a time. This simplifies memory management and makes the interpreter thread-safe.
64. What is the difference between Threading and Multiprocessing in Python?Threading
Multiprocessing
Threading is generally preferred for I/O-bound tasks, while multiprocessing is better suited for CPU-bound tasks. 65. What are async and await in Python?async and await are used to write asynchronous programs that can perform multiple I/O operations concurrently without blocking execution.
Output Hello 66. What are Function Annotations in Python?
67. What is Walrus Operator?Walrus Operator allows 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. It is represented by the `:=` syntax and can be used in a variety of contexts including while loops and if statements.
Output 5 4 3 2 1 68. What is Python Switch Statement?Python does not have a traditional switch statement like languages such as C, C++ or Java. Starting with Python 3.10, however, Python introduced structural pattern matching using the match and case keywords, which provides similar functionality.
Output two Relevant ResourcesTo do well in interviews, you need to understand core syntax, memory management, functions, recursion, data structures and practical coding problems.
Comment Explore | ||||||||||
| You are visitor 01402503 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |