Python Interview Questions and Answers (original) (raw)

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

Python `

a = [1, 2, 3] b = [4, 5, 6] res = a + b print(res)

`

**2. extend() : This adds all the elements of the second list to the first list in-place.

Python `

a = [1, 2, 3] b = [4, 5, 6] a.extend(b) print(a)

`

3.Difference between for loop and while loop in Python

for i in range(5): print(i)

c = 0 while c < 5: print(c) c += 1

`

Output

0 1 2 3 4 0 1 2 3 4

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

import math

n = 3.7 F_num = math.floor(n)

print(F_num)

`

5. 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:

Python `

print(5//2) print(5/2)

`

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

Indentation-in-python

Python Indentation

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

Python `

def add(x, y): return x + y

def apply_func(func, a, b): return func(a, b)

print(apply_func(add, 3, 5))

`

The add function is passed as an argument to apply_func, which applies it to 3 and 5.

8. What is a dynamically typed language?

**Example:

Python `

x = 10 # x is an integer x = "Hello" # Now x is a string

`

Here, the type of x changes at runtime based on the assigned value hence it shows dynamic nature of Python.

9. What is pass in Python?

def fun(): pass # Placeholder, no functionality yet

Call the function

fun()

`

Here, fun() does nothing, but the code stays syntactically correct.

10. How are arguments passed by value or by reference in Python?

You can check the difference between pass-by-value and pass-by-reference in the example below:

Python `

def call_by_val(x): x = x * 2 return x

def call_by_ref(b): b.append("D") return b

a = ["E"] num = 6

Call functions

updated_num = call_by_val(num) updated_list = call_by_ref(a)

Print after function calls

print("Updated value after call_by_val:", updated_num) print("Updated list after call_by_ref:", updated_list)

`

Output

Updated value after call_by_val: 12 Updated list after call_by_ref: ['E', 'D']

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

Python `

s1 = 'GeeksforGeeks'

s2 = lambda func: func.upper() print(s2(s1))

`

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

Python `

a = [2,3,4,5] res = [val ** 2 for val in a] print(res)

`

13. What are *args and **kwargs?

def fun(*argv): for arg in argv: print(arg)

fun('Hello', 'Welcome', 'to', 'GeeksforGeeks')

`

Output

Hello Welcome to GeeksforGeeks

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

14. What is a break, continue and pass in Python?

15. What is the difference between a Set and Dictionary?

my_set = {1, 2, 3}

my_dict = {"a": 1, "b": 2, "c": 3}

16. What are Built-in data types in Python?

The following are the standard or built-in data types in Python:

17. What is the difference between a Mutable datatype and an Immutable data type?

Mutable example

a = [1, 2, 3] a.append(4) print(a)

Immutable example

s = "Hello" s = s + " World" print(s)

`

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

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

19. 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 ordered collection of key-value pairs accessed using unique keys 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}.

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.

def add(a, b): """Return the sum of two numbers.""" return a + b

Access using doc

print(add.doc)

Access using help()

help(add)

`

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

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

Python `

n = 10 try: res = n / 0 # Raises ZeroDivisionError

except ZeroDivisionError: print("Can't be divided by zero!")

finally: print("Execution completed.")

`

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.

22. What is the difference between Python Arrays and Lists?

**Example:

Python `

from array import array arr = array('i', [1, 2, 3, 4]) # Array of integers print(arr)

`

Output

array('i', [1, 2, 3, 4])

**Example:

Python `

a = [1, 'hello', 3.14, [1, 2, 3]] print(a)

`

Output

[1, 'hello', 3.14, [1, 2, 3]]

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

Python `

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.

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

25. What is Dictionary Comprehension? Give an Example

Dictionary Comprehension is a concise way to create dictionaries from existing iterables. It allows you to generate key-value pairs in a single line of code, making the code more readable and efficient.

Python `

keys = ['a', 'b', 'c', 'd', 'e'] values = [1, 2, 3, 4, 5]

Dictionary comprehension

d = {k: v for k, v in zip(keys, values)} print(d)

`

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

Explanation: In Python, expressions enclosed in parentheses with a for loop produce a generator expression, which generates values lazily one at a time. Since tuples are immutable sequences, Python does not provide a separate tuple comprehension syntax. Instead, the recommended approach is to use a generator expression and convert it into a tuple using tuple().

27. Differentiate between List and Tuple?

Let’s analyze the differences between List and Tuple:

**List

**Tuple

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 references of objects to the original memory address. Deep copy stores copies of the object’s value.
Shallow Copy reflects changes made to the new/copied object in the original object. Deep copy doesn’t reflect changes made to the new/copied object in the original object.
Shallow Copy stores the copy of the original object and points the references to the objects. Deep copy stores the copy of the original object and recursively copies the objects as well.
A shallow copy is faster. Deep copy is comparatively slower.

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

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.

Python `

import pdb x = 5 pdb.set_trace() # Debugger starts here print(x)

`

**Output

> /home/repl/02c07243-5df9-4fb0-a2cd-54fe6d597c80/main.py(4)()
-> print(x)
(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).

Python `

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

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

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

multiple_inheritance

Multiple Inheritance

Python does support multiple inheritances, unlike some programming languages that restrict multiple inheritance of classes. For example:

Python `

class A: def method_a(self): print("Method from class A")

class B: def method_b(self): print("Method from class B")

class C(A, B): pass

obj = C() obj.method_a() obj.method_b()

`

Output

Method from class A Method from class B

**Explanation:

35. What is Polymorphism in Python?

Polymorphism means "many forms." It allows the 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.

**Example:

Python `

class Animal: def sound(self): print("Some sound")

class Dog(Animal): def sound(self): print("Bark")

class Cat(Animal): def sound(self): print("Meow")

for animal in [Dog(), Cat()]: animal.sound()

`

**Explanation:

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:

Python achieves encapsulation through public, protected and private attributes.

encapsulation_in_python

Encapsulation

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

**Example:

Python `

from abc import ABC, abstractmethod

class Shape(ABC): @abstractmethod def area(self): pass

class Circle(Shape): def area(self): return 3.14 * 5 * 5

c = Circle() print(c.area())

`

**Explanation:

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.

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.

39. How to delete a file using Python?

Python provides several ways to delete files, some of them are as following:

  1. os.remove() deletes a file permanently.
  2. send2trash.send2trash() moves a file to the recycle bin or trash.
  3. os.rmdir is used to remove empty directories, not files.

40. What is slicing in Python?

Python Slicing is a technique used to extract a portion of a sequence such as a string, list, tuple or range. It allows you to specify a starting index, an ending index and an optional step value.

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

type_of_namespaces

Namespace

**Types of Namespaces:

  1. **Built-in Namespace: Contains all the built-in functions and exceptions, like print(), int(), etc. These are available in every 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.

Advanced Python Interview Questions & Answers

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

Example:

pip install numpy

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. What are Pickling and Unpickling?

45. What is the difference between @classmethod, @staticmethod and instance methods in Python?

Example:

Python `

class Student: school = "ABC School"

# Instance method
def display(self, name):
    print(f"Student Name: {name}")

# Class method
@classmethod
def show_school(cls):
    print(f"School: {cls.school}")

# Static method
@staticmethod
def is_adult(age):
    return age >= 18

s = Student()

Instance method

s.display("Kevin")

Class method

Student.show_school()

Static method

print(Student.is_adult(20))

`

Output

Student Name: Kevin School: ABC School True

46. What is __init__() in Python and how does self play a role in it?

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

`

47. Write a code to display the current time?

Python `

from datetime import datetime print("Current time is:", datetime.now())

`

Output

Current time is: 2026-05-11 11:10:41.581886

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:

**Example:

Python `

class Student: def init(self): # Public self.name = "Mike"
# Protected self._roll_no = 101
# Private self.__marks = 95

obj = Student() print(obj.name)
print(obj._roll_no) print(obj._Student__marks)

`

**Explanation:

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

51. What are Function Annotations in Python?

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

Python `

try: raise ExceptionGroup( "Example ExceptionGroup", [ TypeError("Example TypeError"), ValueError("Example ValueError"), KeyError("Example KeyError"), AttributeError("Example AttributeError"), ] ) except* TypeError: print("Handled TypeError") except* ValueError: print("Handled ValueError") except* (KeyError, AttributeError): print("Handled KeyError and AttributeError")

`

Output

Handled TypeError Handled ValueError Handled KeyError and AttributeError

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

Python `

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?

**Note: Python versions before 3.8 doesn't support Walrus Operator.

Python `

numbers = [1, 2, 3, 4, 5]

while (n := len(numbers)) > 0: print(numbers.pop())

`

Topic-wise Interview Questions:

Relevant Resources

To do well in interviews, you need to understand core syntax, memory management, functions, recursion, data structures and practical coding problems.

  1. **Core Concepts: Strings, Lists, Tuples, Sets, Dictionaries. Pointers, Scope of Variables, Type Casting, File Handling, Memory Management
  2. **Advanced Topics: OOPs Concepts, Decorators, Generators, Lambda Functions, Packages, Class method vs Static method, Mutable vs Immutable Objects, Global Interpreter Lock.