Python Interview Questions

1. What are mutable and immutable data types in Python? Provide examples.

Answer:

  • Mutable data types can be changed after they are created, like lists (list), dictionaries (dict), and sets (set).
  • Immutable data types cannot be changed after they are created, like integers (int), strings (str), and tuples (tuple).
Example: 
Lists are mutable (my_list[0] = 'new_value'), 
while strings are immutable (my_str[0] = 'n' will raise an error).
2. How is a Python dictionary different from a list?

Answer:

  • A list is an ordered collection of elements accessed by index.
  • A dictionary is an unordered collection of key-value pairs, where data is accessed using a unique key rather than an index.
Example:
List: my_list[0], Dictionary: my_dict['key']
3. Explain the difference between is and == when comparing data types in Python.

Answer:

  • == checks if two objects have the same value.
  • is checks if two objects refer to the same memory location.
Example:                            
Two lists with the same content (list1 == list2 is True) may still occupy different memory locations (list1 is list2 is False).
4. What is the difference between a tuple and a list? When would you use a tuple over a list?

Answer:

  • A list is mutable (its elements can be modified), while a tuple is immutable (its elements cannot be changed once assigned).
  • Use a tuple when you need to store data that should not be altered, such as constant values. Use a list for dynamic data where modifications are needed.
5. How does Python handle the conversion between different data types? Give an example of type casting?

Answer: Python allows type casting using built-in functions like int(), float(), str(), etc., to convert between data types.

        
Example: 
Converting a float to an integer: int(4.75) results in 4. 
Converting a string to an integer: int('123') results in 123.
6. What are the different types of operators in Python?

Answer: Python supports arithmetic, comparison, logical, bitwise, assignment, identity, and membership operators.

7. How does the floor division operator // differ from regular division / in Python?

Answer:

// performs floor division and returns the largest integer less than or equal to the result, while / performs regular division and returns a float.

8. What is the difference between and and & operators in Python?

Answer:and is a logical operator that evaluates to True if both conditions are True, while & is a bitwise operator that performs AND operation at the binary level.

9. How does Python handle the precedence of operators in expressions?

Answer:

Python evaluates operators based on their precedence, with higher precedence operators (like *, /) being evaluated before lower precedence operators (like +, -). Parentheses can be used to override the default precedence.

10. How does Python handle variable scope within functions?

Answer:

Python uses LEGB (Local, Enclosing, Global, Built-in) rule for variable scope. Variables declared inside a function are local to that function unless declared global.

11. What is the difference between a global variable and a local variable in Python?

Answer:

A global variable is declared outside all functions and is accessible throughout the program, while a local variable is declared inside a function and is only accessible within that function.

Example:

# Global Variable
x = 10  # Global variable

def my_function():
    # Local Variable
    y = 5  # Local variable
    print("Inside function, local y:", y)
    print("Inside function, global x:", x)  # Accessing the global variable inside the function

my_function()
# Trying to access local variable outside function
print("Outside function, global x:", x)  # Can access global variable
# print(y)  # This will raise an error because y is a local variable
Output
Inside function, local y: 5
Inside function, global x: 10
Outside function, global x: 10
12. How do you declare a variable without specifying its type in Python?

Answer:

Python is dynamically typed, so you declare a variable simply by assigning a value to it,
e.g., x = 10. The variable’s type is determined at runtime.

13. What is variable shadowing in Python?

Answer:

Variable shadowing occurs when a local variable in a function has the same name as a global variable. The local variable temporarily “shadows” the global variable within the function’s scope.

14. Can you assign multiple variables in a single line in Python? Give an example

Answer:

Yes, you can assign multiple variables in a single line like this:
a, b, c = 1, 2, 3.

15. How is a Python list different from an array in other programming languages?

Answer:A Python list can store elements of different data types, while arrays in languages like C or Java typically store only one type of data

16. How do you access elements from a list using positive and negative indexing?

Answer:

Positive indexing starts from 0, where list[0] is the first element.
Negative indexing starts from -1, where list[-1] is the last element.

example:
my_list = ['apple', 'banana', 'cherry', 'date', 'elderberry']

#Accessing elements using positive indexing
print(my_list[0])  # First element
print(my_list[2])  # Third element

my_list = ['apple', 'banana', 'cherry', 'date', 'elderberry']
# Accessing elements using negative indexing
print(my_list[-1])  # Last element
print(my_list[-3])  # Third element from the end
17. How can you modify an element in a list?

Answer:You can modify an element by accessing it via its index and assigning a new value.

Example:
my_list[2] = 'new_value'
18. What happens if you try to access an index that is out of range in a list?

Answer:

Python raises an IndexError if you attempt to access an index that is beyond the range of the list.

19. How do you concatenate two lists in Python without using any built-in functions?

Answer:

You can concatenate two lists using the + operator, like this: list1 + list2.

20. What is the main difference between a tuple and a list?

Answer:

A tuple is immutable (cannot be changed after creation), <>br> while a list is mutable (can be changed).

21. Can you change an element in a tuple?

Answer:

No, tuples are immutable, so you cannot modify their elements after they are created.

22. How do you access elements in a tuple?

Answer:

Elements in a tuple are accessed via indexing, just like lists. For example, my_tuple[1] returns the second element.

23. Can a tuple contain elements of different data types?

Answer:

Yes, tuples can store elements of different data types, similar to lists.

24. How can you create a tuple with a single element?

Answer:

You can create a tuple with a single element by adding a comma after the element, like this: (5,).

25. How are dictionaries different from lists in Python?

Answer:

A dictionary stores key-value pairs, while a list stores a sequence of values. Dictionary keys are unique, and values are accessed using keys, not indices.

26. How do you add a key-value pair to a dictionary?

Answer:

You can add a key-value pair by assigning a value to a key.

Example: 

my_dict['new_key'] = 'new_value'
27. What happens if you try to access a key that doesn’t exist in a dictionary?

Answer:

Python raises a KeyError if you try to access a key that is not present in the dictionary.

28. Can a dictionary key be of any data type?

Answer:

No, dictionary keys must be immutable data types like strings, numbers, or tuples. Lists cannot be used as dictionary keys.

29. How are dictionaries ordered in Python 3.7+?

Answer:

Starting from Python 3.7, dictionaries maintain insertion order, meaning the order in which key-value pairs are added is preserved.

30. What is a set in Python, and how is it different from a list?

Answer:

A set is an unordered collection of unique elements, while a list is ordered and can contain duplicate values.

31.Can a set contain duplicate elements?

Answer:

No, sets automatically remove duplicates, ensuring that each element is unique.

32. How do you add an element to a set in Python?

Answer:

You can add an element using the add() method, like this: my_set.add(‘element’).

33. How does Python handle ordering of elements in a set?

Answer:

Sets are unordered collections, so the elements do not have a defined order and cannot be accessed via indexing.

34. Can a set contain elements of different data types?

Answer:

Yes, sets can contain elements of different data types, as long as they are immutable (e.g., integers, strings, tuples).

35. What is the difference between a function and a method in Python?

Answer:

function is a block of reusable code that performs a specific task and is defined using the def keyword. It can be called from anywhere in the program.
method is a function that is associated with an object or class. It is called on an object, and its behavior can depend on the object’s state.

Example:
# Function
def greet():
    return "Hello, World!"
# Method (associated with a string object)
s = "Hello"
print(s.lower())  # Calling a method on a string object
36. How can you pass default arguments to a function? Give an example

Answer:

In Python, you can define default values for function parameters. If the function is called without arguments for those parameters, the default values are used.

Example:
def greet(name="Guest"):
    return f"Hello, {name}!"

print(greet())        # Output: Hello, Guest!
print(greet("Alice")) # Output: Hello, Alice!
37. What is variable-length argument (*args and kwargs) in Python functions?

Answer:

*args allows a function to accept any number of positional arguments.
**kwargs allows a function to accept any number of keyword arguments.

 Example:
 def demo_args(*args):
    for arg in args:
        print(arg)

def demo_kwargs(**kwargs):
    for key, value in kwargs.items():
        print(f"{key}: {value}")

demo_args(1, 2, 3)             # Output: 1, 2, 3
demo_kwargs(name="John", age=30) # Output: name: John, age: 30
38. What is a lambda function in Python, and how is it different from a regular function?

Answer:

A lambda function is a small, anonymous function defined using the lambda keyword. It can have any number of arguments but only one expression. Lambda functions are often used for short, throwaway functions.

Example:
# Regular function
def add(x, y):
    return x + y
# Lambda function
add_lambda = lambda x, y: x + y
print(add(3, 4))        # Output: 7
print(add_lambda(3, 4)) # Output: 7tu
39. What is the purpose of return in a function? Can a function return multiple values?

Answer:

The return statement in a function sends the result of the function back to the caller and terminates the function execution. Yes, a function can return multiple values by separating them with commas, and these values are returned as a tuple.

Example:
def get_details():
    name = "John"
    age = 25
    return name, age  # Returning multiple values as a tuple
result = get_details()
print(result)        # Output: ('John', 25)
print(result[0])     # Output: John
print(result[1])     # Output: 25
40. What is a Python package, and how is it different from a module?

Answer:

A module is a single Python file containing functions, classes, or variables, whereas a package is a collection of modules grouped together in a directory, often with an __init__.py file.

41. How do you install third-party Python packages?.

Answer:

Third-party Python packages can be installed using pip, the package manager for Python.

 Example:
 pip install requests
42. How do you import a specific function from a module within a package?

Answer:

You can import a specific function using the from keyword.

Example:
from my_package.my_module import my_functionty
43. How do you create your own Python package?

Answer:

To create a package, organize your code into modules (Python files), place them in a directory, and include an __init__.py file. The __init__.py file can be empty or contain initialization code.

44. How do you check the list of installed packages in your environment?

Answer:

You can use pip list to view all installed packages in your Python environment.

45. What is Object-Oriented Programming (OOP) in Python?

Answer:

OOP is a programming paradigm based on the concept of “objects”, which are instances of classes. It allows for encapsulation, inheritance, and polymorphism.

46. What is the purpose of the __init__() method in Python classes?

Answer:

The __init__() method is a constructor used to initialize the object’s attributes when a new instance of a class is created.

47. Explain inheritance in Python with an example.

Answer:

Inheritance allows a class to inherit properties and methods from another class.

Example:
class Animal:
    def speak(self):
        return "Animal speaks"

class Dog(Animal):
    def bark(self):
        return "Dog barks"

d = Dog()
print(d.speak())  # Inherits speak method
48. What is the difference between class variables and instance variables?

Answer:

Class variables are shared among all instances of a class, while instance variables are unique to each instance.

49. What is polymorphism in Python?

Answer:

Polymorphism allows different classes to implement the same method in different ways.
Example: A Dog and Cat class can both implement a speak() method, but the method behaves differently in each class

50. How is encapsulation achieved in Python?

Answer:

Encapsulation is achieved by restricting access to certain attributes or methods using private (__) or protected (_) access modifiers.

51. Explain multiple inheritance in Python with an example.

Answer:

Multiple inheritance allows a class to inherit from more than one class.

 Example:

 class A:
    def method_a(self):
        return "Method A"
class B:
    def method_b(self):
        return "Method B"
class C(A, B):
    pass
c = C()
print(c.method_a(), c.method_b())
52. What is method overriding in Python?

Answer:

Method overriding occurs when a subclass provides a specific implementation of a method that is already defined in its superclass.

53. What is the difference between @staticmethod and @classmethod in Python?

Answer:

@staticmethod: A method that does not modify class or instance state. It doesn’t take self or cls as arguments.
@classmethod: A method that takes cls as its first argument and can modify class-level state.

54. Can you explain the difference between composition and inheritance in Python OOPs?

Answer:

Inheritance models an “is-a” relationship, where a subclass inherits properties and methods from a superclass.
Composition models a “has-a” relationship, where an object contains other objects as attributes.

55. What is operator overloading in Python?

Answer:

Operator overloading allows you to define custom behavior for operators (e.g., +, -, *, ==) in your own classes by implementing special methods like __add__(), __eq__(), etc.

56. How would you overload the + operator in a Python class?

Answer:

By defining the __add__() method in the class.

Example:
Example:
class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __add__(self, other):
        return Point(self.x + other.x, self.y + other.y)
57. Can you overload the equality == operator in Python?

Answer:

Yes, by defining the __eq__() method in your class.

58. What happens if you try to compare objects of different classes with operator overloading?

Answer:

You need to handle type-checking inside the overloaded method to avoid comparison errors. Otherwise, it may result in a TypeError.

59. Can you overload the [] indexing operator in Python? If so, how?

Answer:

Yes, by defining the __getitem__() and __setitem__() methods, you can overload the indexing operator.

60. What is the purpose of exception handling in Python?

Answer:

Exception handling allows you to manage runtime errors gracefully, preventing the program from crashing by using try, except, finally, and raise.

61. How do you raise an exception in Python?

Answer:

You can raise an exception using the raise keyword.

 Example:

 raise ValueError("Invalid value")
62. What is the difference between try-except and try-finally in Python?

Answer:

try-except handles exceptions that occur within the try block.
try-finally guarantees that the finally block will be executed whether or not an exception occurs.

63. Can you have multiple except blocks in Python?

Answer:

Yes, you can have multiple except blocks to handle different types of exceptions.

64. What is the purpose of the else block in Python's exception handling?

Answer:

The else block is executed if no exceptions are raised in the try block.

65. What is a regular expression in Python, and which module is used for it?

Answer:

A regular expression (RegEx) is a pattern used to match strings. Python’s re module provides functions for working with regular expressions.

66. How would you search for a pattern in a string using regular expressions?

Answer:

You can use the re.search() function

Example:
import re
match = re.search(r'\d+', 'abc123')
67. How can you replace all occurrences of a pattern in a string using RegEx?

Answer:

You can use the re.search() function

Example:
import re
match = re.search(r'\d+', 'abc123')
68. What does the \d, \w, and \s special sequences represent in Python RegEx?

Answer:

\d: Matches any digit (0-9).
\w: Matches any word character (alphanumeric and underscore).
\s: Matches any whitespace character.

69. How do you split a string using a regular expression?

Answer:

You can use re.split() to split a string by a regular expression pattern..

 Example:
 import re

# String with multiple delimiters (commas, semicolons, spaces)
text = "apple, banana; cherry orange"

# Use regular expression to split by commas, semicolons, or spaces
result = re.split(r'[,\s;]+', text)

print(result)

#Output
['apple', 'banana', 'cherry', 'orange']
70. How do you open a file in Python? Explain the different modes available?

Answer:

You can use the open() function to open a file. Modes include:
‘r’: Read (default)
‘w’: Write
‘a’: Append
‘b’: Binary mode

71. How do you read an entire file into memory in Python?

Answer:

You can use the read() method to read the entire contents of a file into memory.

 Example:
 with open('file.txt', 'r') as f:
    content = f.read()
72. What is the difference between read() and readline() when reading a file?

Answer:

read() reads the entire file.
readline() reads one line at a time.

73. Explain how the super() function works in Python. Can you provide an example of its usage in a multiple inheritance scenario?

Answer:

super() is used to call a method from the parent class. It is particularly useful in multiple inheritance scenarios to ensure that the method resolution order (MRO) is followed correctly.

 Example:
 class A:
    def __init__(self):
        print("A's __init__")
        
class B(A):
    def __init__(self):
        super().__init__()
        print("B's __init__")

class C(A):
    def __init__(self):
        super().__init__()
        print("C's __init__")

class D(B, C):
    def __init__(self):
        super().__init__()
        print("D's __init__")
d = D()

Output:
A's __init__
C's __init__
B's __init__
D's __init__
In this example, super() ensures that A's __init__ is only called once, despite the multiple inheritance.
74. What is Duck Typing in Python? Can you provide an example?

Answer:

Duck typing is a concept related to dynamic typing in Python. It means that the suitability of an object is determined by the presence of certain methods and properties, rather than the actual type of the object.

 Example:
 class Duck:
    def quack(self):
        print("Quack!")
        
class Person:
    def quack(self):
        print("I'm quacking like a duck!")
        
def in_the_forest(duck):
    duck.quack()
    
d = Duck()
p = Person()

in_the_forest(d)  # Quack!
in_the_forest(p)  # I'm quacking like a duck!

In this example, both Duck and Person objects can be passed to in_the_forest() function because they both have a quack method.
75. What is the match statement in Python, and how is it used? Can you provide an example?

Answer:

The match statement is a feature introduced in Python 3.10, used for structural pattern matching. It allows for checking a value against a pattern

 Example:
 def http_status(status):
    match status:
        case 200:
            return "OK"
        case 404:
            return "Not Found"
        case 500:
            return "Internal Server Error"
        case _:
            return "Unknown status"

print(http_status(200))  # OK
print(http_status(404))  # Not Found
print(http_status(500))  # Internal Server Error
print(http_status(403))  # Unknown status
76. How can you reverse a string in Python?

Answer:

There are many ways to a reverse a string in Python one way is using slicing.

 Example:
 s = "Hello, World!"
reversed_s = s[::-1]
print(reversed_s)  # !dlroW ,olleH
77. How does the map() function work in Python? Can you provide an example?

Answer:

The map() function applies a given function to all items in an iterable (like a list) and returns a map object (an iterator).

 Example:
 def square(n):
    return n * n

numbers = [1, 2, 3, 4, 5]
squared_numbers = map(square, numbers)
print(list(squared_numbers))  # [1, 4, 9, 16, 25]
78. What are instance variables and class variables in Python? Can you provide an example?

Answer:

Instance Variables are variables that are specific to each object. They are defined in the __init__ method and are prefixed with self.

Class Variables are variables that are shared among all instances of a class. They are defined within the class but outside any methods.

 Example:
 class Dog:
    species = "Canis familiaris"  # Class Variable
    
    def __init__(self, name, age):
        self.name = name  # Instance Variable
        self.age = age    # Instance Variable

dog1 = Dog("Buddy", 5)
dog2 = Dog("Molly", 7)

print(dog1.species)  # Canis familiaris
print(dog2.species)  # Canis familiaris
print(dog1.name)     # Buddy
print(dog2.name)     # Molly
79. What is method overriding in Python? Can you provide an example?

Answer:

Method overriding occurs when a subclass provides a specific implementation for a method that is already defined in its superclass. The method in the subclass should have the same name and signature as the method in the superclass.

 Example:
 class Animal:
    def sound(self):
        return "Some sound"
    
class Dog(Animal):
    def sound(self):
        return "Bark"

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

dog = Dog()
cat = Cat()

print(dog.sound())  # Bark
print(cat.sound())  # Meow

In this example, the sound method is overridden in the Dog and Cat subclasses to provide specific sounds.