Interview Questions

1) What is Python?


Python is a high-level, interpreted programming language that was created by Guido van Rossum and first released in 1991. It is known for its easy-to-read syntax, simplicity, and readability. Python supports multiple programming paradigms, including procedural, object-oriented, and functional programming. It has a large standard library, making it versatile and easy to use for tasks ranging from web development to machine learning, data analysis, automation, and more.

2) How do you print something in Python?


To print something in Python, we use the built-in print() function. It allows you to display data, including strings, variables, and calculations. Here’s an example:

print("Hello, World!")  # Output: Hello, World!
print(5 + 3)            # Output: 8

The print() function can also be used to print multiple values, separated by commas.

3) What are Python data types?


Python provides several built-in data types for different purposes. Here are the most common ones:

  • int: Integer values (e.g., 1, -5, 42).
  • float: Decimal numbers (e.g., 3.14, -2.5).
  • str: Strings (e.g., "hello", "Python").
  • list: Ordered, mutable collections of items (e.g., [1, 2, 3, 4]).
  • tuple: Ordered, immutable collections of items (e.g., (1, 2, 3)).
  • set: Unordered collections of unique items (e.g., {1, 2, 3}).
  • dict: Unordered collection of key-value pairs (e.g., {"name": "Alice", "age": 25}).
  • bool: Boolean values (True or False).
  • None: A special type used to represent the absence of a value.

4) What is the difference between a list and a tuple?


The primary difference between lists and tuples in Python is that lists are mutable (they can be modified after creation), while tuples are immutable (once created, they cannot be changed). This makes tuples more efficient in terms of memory usage and performance. Lists are typically used when you need a collection of items that can be modified, whereas tuples are often used for fixed collections of items.

my_list = [1, 2, 3]    # List
my_tuple = (1, 2, 3)   # Tuple

 

5) What is a dictionary in Python?


A dictionary in Python is an unordered collection of key-value pairs. Each key is unique, and each key is associated with a value. Dictionaries are defined using curly braces {} with key-value pairs separated by colons (:). Example:

my_dict = {"name": "Alice", "age": 25}
print(my_dict["name"])  # Output: Alice

You can also use various methods like keys(), values(), and items() to interact with dictionaries.

6) How do you define a function in Python?


Functions in Python are defined using the def keyword. A function can accept arguments, perform operations, and return a result. Functions help to organize code and avoid redundancy.

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

print(greet("Alice"))  # Output: Hello, Alice!

Functions can return values using the return statement, and if no return statement is provided, None is returned by default.

7) What are comments in Python?


Comments in Python are lines that are ignored by the interpreter and are used to add notes to the code. They help to explain the code, making it more readable and easier to understand.

  • Single-line comments begin with the hash symbol (#).
  • Multi-line comments can be written using triple quotes (''' or """). Example:
    # This is a single-line comment
    print("Hello, World!")  # This prints a message
    
    '''
    This is a
    multi-line comment
    explaining the code
    '''
    

     

8) What is a variable in Python?


A variable in Python is a symbolic name that refers to a value stored in memory. Python is dynamically typed, which means you don't need to declare the type of a variable before using it. A variable can store various types of data like numbers, strings, lists, etc. You can assign values to variables using the = operator.

x = 10       # Integer
name = "John"  # String

 

9) What is type casting in Python?


Type casting is the process of converting one data type to another. In Python, this is done explicitly using built-in functions like int(), float(), str(), etc. For example, you can convert a float to an integer or an integer to a string.

x = int(3.14)  # Converts float to integer, result: 3
y = str(10)    # Converts integer to string, result: '10'

 

10) What is the difference between == and is?


  • == checks for value equality. It returns True if the values of the two objects are the same.
  • is checks for identity. It returns True if both variables refer to the same object in memory (i.e., they are the exact same object). Example:
    x = [1, 2, 3]
    y = [1, 2, 3]
    z = x
    
    print(x == y)  # True (values are the same)
    print(x is y)  # False (they are different objects in memory)
    print(x is z)  # True (both refer to the same object)
    

     

11) What are conditional statements in Python?


Conditional statements in Python allow you to make decisions based on whether a condition is True or False. The basic structure uses if, elif, and else to execute different blocks of code.

age = 20
if age >= 18:
    print("Adult")
else:
    print("Minor")

 

12) What is a for loop in Python?


The for loop is used to iterate over a sequence (like a list, tuple, or range) and execute a block of code multiple times. Python's for loop works by iterating directly over the elements of a sequence.

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

The loop will iterate from 0 to 4 (the range is exclusive of the upper limit).

13) What is a while loop in Python?


The while loop repeats a block of code as long as the given condition is True. The condition is evaluated before every iteration, so if it’s False initially, the loop may never execute.

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

 

14) What is the break statement in Python?


The break statement is used to exit a loop prematurely. It can be used in both for and while loops to terminate the loop before the condition becomes False.

for i in range(10):
    if i == 5:
        break
    print(i)  # Output: 0 1 2 3 4

 

15) What is the continue statement in Python?


The continue statement is used to skip the current iteration of a loop and move to the next iteration. It is useful when you want to skip certain elements based on a condition but still continue looping.

for i in range(5):
    if i == 3:
        continue
    print(i)  # Output: 0 1 2 4

 

16) What is the pass statement in Python?


The pass statement is a null operation used as a placeholder where syntactically required but no action is needed. It is often used in functions, loops, or conditionals that are yet to be implemented.

def my_function():
    pass  # Function does nothing yet

 

17) What is list comprehension in Python?


List comprehension provides a concise way to create lists by applying an expression to each item in an iterable, optionally filtering the items.

squares = [x**2 for x in range(5)]
print(squares)  # Output: [0, 1, 4, 9, 16]

 

18) How do you create a list in Python?


A list in Python can be created using square brackets [] with elements separated by commas. Lists are mutable and can contain mixed data types.

my_list = [1, 2, 3, 4, 5]
print(my_list)  # Output: [1, 2, 3, 4, 5]

 

19) How do you access elements in a list?


Elements in a list can be accessed using indices. The index starts from 0 for the first element.

my_list = [10, 20, 30]
print(my_list[1])  # Output: 20

 

20) What is a set in Python?


A set in Python is an unordered collection of unique elements. Sets do not allow duplicate values and are defined using curly braces {}. They are mutable and are commonly used for membership tests and removing duplicates from a list.

my_set = {1, 2, 3, 4}
print(my_set)  # Output: {1, 2, 3, 4}
my_set.add(5)  # Adds element 5 to the set

 

21) What is the difference between list and set in Python?


  • A list is an ordered collection of items, where duplicates are allowed, and the items are indexed.
  • A set is an unordered collection of unique elements, with no indexing and no duplicate elements. Sets are typically used when you need to store unique values without worrying about order. Example:
    list_example = [1, 2, 2, 3]
    set_example = {1, 2, 2, 3}
    print(list_example)  # Output: [1, 2, 2, 3]
    print(set_example)   # Output: {1, 2, 3}
    

     

22) How do you handle exceptions in Python?


Python provides a mechanism for handling errors and exceptions using try, except, and optionally finally. This allows you to catch specific errors, handle them appropriately, and clean up resources if necessary.

try:
    x = 10 / 0
except ZeroDivisionError as e:
    print("Error:", e)  # Output: Error: division by zero
finally:
    print("Execution complete.")  # Always executes

 

23) What is the purpose of the else block in a try-except?


The else block in a try-except structure is executed if no exception is raised in the try block. It is commonly used for code that should run only when no errors occur.

try:
    x = 10 / 2
except ZeroDivisionError:
    print("Cannot divide by zero")
else:
    print("Division successful.")  # Output: Division successful.

 

24) What is the finally block in Python?


The finally block is always executed, regardless of whether an exception occurred or not. It is typically used for cleanup actions, like closing files or releasing resources.

try:
    f = open("file.txt", "r")
except IOError:
    print("File not found")
finally:
    f.close()  # Always executed to close the file, even if an error occurs

 

25) What is a lambda function in Python?


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 that are not meant to be reused.

add = lambda x, y: x + y
print(add(2, 3))  # Output: 5

 

26) What are the advantages of using a lambda function?


Lambda functions provide a concise way to write small functions without the need to define a full function using def. They are commonly used when passing a simple function as an argument to higher-order functions like map(), filter(), and sorted(). Example with map():

numbers = [1, 2, 3, 4]
squared = list(map(lambda x: x ** 2, numbers))
print(squared)  # Output: [1, 4, 9, 16]

 

27) What is a generator in Python?


A generator is a special type of iterable that generates values one at a time using the yield keyword. It allows you to iterate over data without storing the entire dataset in memory, which is memory efficient, especially with large data.

def count_up_to(n):
    count = 1
    while count <= n:
        yield count
        count += 1

counter = count_up_to(5)
for num in counter:
    print(num)  # Output: 1 2 3 4 5

 

28) What is the yield keyword in Python?


The yield keyword is used in functions to create generators. It allows the function to return an intermediate result and pause its execution, resuming from the last yield when called again. This allows for memory-efficient iteration over large datasets.

def my_generator():
    yield 1
    yield 2
    yield 3

for value in my_generator():
    print(value)  # Output: 1 2 3

 

29) What are Python modules and packages?


A module is a file containing Python code that can define functions, classes, and variables. A package is a collection of modules grouped together in a directory hierarchy. Python allows you to import these modules and packages into your code to reuse functionality.

  • Module Example:
    import math
    print(math.sqrt(16))  # Output: 4.0
    
  • Package Example: A package can be imported like this:
    from mypackage import mymodule
    

 

30) How do you import a module in Python?


You can import a module in Python using the import statement. There are different ways to import modules:

  • Basic import:
    import math
    print(math.pi)
    
  • Import specific functions or classes:
    from math import sqrt
    print(sqrt(16))  # Output: 4.0
    
  • Alias for module:
    import numpy as np
    

     

31) What is the __init__ method in Python classes?


The __init__ method is a special method in Python classes that is called when an object is instantiated. It is the constructor method, used to initialize the object’s attributes.

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

person = Person("Alice", 30)
print(person.name)  # Output: Alice

 

32) What is inheritance in Python?


Inheritance is a fundamental concept in object-oriented programming where one class (child class) inherits attributes and methods from another class (parent class). It allows for code reusability and is implemented using parentheses when defining the child class.

class Animal:
    def speak(self):
        print("Animal speaks")

class Dog(Animal):
    def speak(self):
        print("Dog barks")

dog = Dog()
dog.speak()  # Output: Dog barks

 

33) What is polymorphism in Python?


Polymorphism allows objects of different classes to be treated as instances of the same class. It enables the same method name to work differently depending on the class that it is acting upon. In Python, polymorphism is achieved through method overriding and dynamic method calls.

class Cat:
    def speak(self):
        print("Meow")

class Dog:
    def speak(self):
        print("Woof")

animals = [Cat(), Dog()]
for animal in animals:
    animal.speak()  # Output: Meow  Woof

 

34) What is encapsulation in Python?


Encapsulation is the concept of bundling data and methods that operate on that data within a single unit (class) and restricting access to some of the object's components. This is achieved using private and public attributes and methods. In Python, this is done using underscores: one underscore _ for protected members and two underscores __ for private members.

class Car:
    def __init__(self, model):
        self.model = model  # public attribute
        self.__speed = 0  # private attribute

    def start_engine(self):
        print(f"{self.model} engine started.")
    
    def get_speed(self):
        return self.__speed  # private attribute access

my_car = Car("Toyota")
my_car.start_engine()
print(my_car.get_speed())  # Accessing private method

 

35) What is abstraction in Python?


Abstraction is a concept that hides the complexity and shows only the essential features of an object. It is implemented using abstract classes in Python, which cannot be instantiated directly. The abc module in Python is used to create abstract classes and methods.

from abc import ABC, abstractmethod

class Animal(ABC):
    @abstractmethod
    def sound(self):
        pass

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

dog = Dog()
dog.sound()  # Output: Woof

 

36) What is a class in Python?


A class in Python is a blueprint for creating objects (instances). It defines a set of attributes and methods that the objects created from the class will have. Classes are fundamental in object-oriented programming (OOP), allowing for encapsulation, inheritance, and polymorphism.

class Car:
    def __init__(self, brand, model):
        self.brand = brand
        self.model = model
    
    def start(self):
        print(f"The {self.brand} {self.model} is starting.")

car = Car("Toyota", "Corolla")
car.start()  # Output: The Toyota Corolla is starting.

 

37) What is object-oriented programming (OOP) in Python?


Object-Oriented Programming (OOP) in Python is a programming paradigm that uses objects and classes to organize code. OOP principles include:

  • Encapsulation: Bundling data and methods together.
  • Inheritance: A class can inherit methods and attributes from another class.
  • Polymorphism: Methods can behave differently based on the object type.
  • Abstraction: Hiding complex implementation details and exposing only essential features. OOP helps in organizing code, improving reusability, and making code easier to maintain.

38) What is slicing in Python?


Slicing allows you to extract a portion of a list, string, or tuple by specifying a start index, end index, and an optional step. The syntax is [start:end:step].

my_list = [10, 20, 30, 40, 50]
print(my_list[1:4])  # Output: [20, 30, 40]

 

39) What is the purpose of self in Python classes?


The self keyword in Python is used to refer to the instance of the class. It allows access to the instance's attributes and methods within the class. Every method in a class requires self as its first parameter to reference the object it is being called on.

class Dog:
    def __init__(self, name):
        self.name = name  # `self` refers to the instance
    
    def bark(self):
        print(f"{self.name} says Woof!")

dog = Dog("Buddy")
dog.bark()  # Output: Buddy says Woof!

 

40) What is a method in Python?


A method in Python is a function that is defined within a class and is associated with an object of that class. Methods typically operate on the instance (using self) and can modify its state or perform actions.

class Person:
    def greet(self):
        print("Hello!")
    
person = Person()
person.greet()  # Output: Hello!

 

41) What is the difference between a class and an object in Python?


  • A class is a blueprint for creating objects, which defines a set of attributes and methods.
  • An object is an instance of a class. When you create an object from a class, the object has access to the class's attributes and methods. Example:
    class Car:
        def __init__(self, model):
            self.model = model
    
    car1 = Car("Tesla")
    car2 = Car("BMW")
    

     

42) How do you create an object from a class in Python?


You create an object by calling the class as if it were a function, passing any required arguments to the __init__ method (the constructor). The constructor initializes the object's attributes.

class Dog:
    def __init__(self, name):
        self.name = name

my_dog = Dog("Rex")  # Creates an object of the Dog class
print(my_dog.name)  # Output: Rex

 

43) What is the difference between __str__ and __repr__ in Python?


  • __str__: It is used to define a human-readable string representation of an object, typically for printing or displaying to users. It should return a string that is easy to understand.
  • __repr__: It is used to define a formal string representation of an object, aimed at developers. The goal is to return a string that can be used to recreate the object (if possible). Example:
    class Car:
        def __init__(self, brand, model):
            self.brand = brand
            self.model = model
        
        def __str__(self):
            return f"Car: {self.brand} {self.model}"
        
        def __repr__(self):
            return f"Car('{self.brand}', '{self.model}')"
    
    car = Car("Toyota", "Camry")
    print(str(car))  # Output: Car: Toyota Camry
    print(repr(car))  # Output: Car('Toyota', 'Camry')
    

     

44) What are class methods and static methods in Python?


  • Class methods: Defined using the @classmethod decorator, these methods take the class (cls) as the first parameter and can modify the class state. They are often used for factory methods.
  • Static methods: Defined using the @staticmethod decorator, static methods don't take self or cls as the first parameter. They are used when a method doesn't need to access the instance or class state. Example:
    class MyClass:
        @classmethod
        def class_method(cls):
            print("This is a class method")
        
        @staticmethod
        def static_method():
            print("This is a static method")
    
    MyClass.class_method()  # Output: This is a class method
    MyClass.static_method()  # Output: This is a static method
    

     

45) What are the super() function and its purpose in Python?


The super() function is used to call a method from the parent class in a derived class. It is commonly used in the __init__ method to initialize the parent class's attributes or to call overridden methods.

class Animal:
    def __init__(self, name):
        self.name = name

class Dog(Animal):
    def __init__(self, name, breed):
        super().__init__(name)  # Calls the parent class's __init__ method
        self.breed = breed

dog = Dog("Buddy", "Golden Retriever")
print(dog.name)  # Output: Buddy

 

46) What are Python decorators?


A decorator in Python is a function that modifies the behavior of another function or method. Decorators are used to extend or alter the behavior of the functions or methods without modifying the actual code. Decorators are often used for logging, authentication, and memoization. They are applied using the @decorator_name syntax. Example:

def decorator_function(func):
    def wrapper():
        print("Before function execution")
        func()
        print("After function execution")
    return wrapper

@decorator_function
def say_hello():
    print("Hello!")

say_hello()  # Output: Before function execution
             # Hello!
             # After function execution

 

47) What are Python iterators?


An iterator in Python is an object that implements the __iter__() and __next__() methods, enabling you to iterate over a collection of items. Iterators allow you to loop through a sequence (like a list or string) without using indexing. Example:

my_list = [1, 2, 3]
my_iterator = iter(my_list)

print(next(my_iterator))  # Output: 1
print(next(my_iterator))  # Output: 2

 

48) How does the for loop work with iterators?


When you use a for loop with an iterable object, Python automatically calls the __iter__() method on the object to get an iterator and then uses the __next__() method to access the elements. This process continues until the iterator raises a StopIteration exception. Example:

my_list = [1, 2, 3]
for item in my_list:
    print(item)
# Output: 1
# Output: 2
# Output: 3

 

49) What are Python's built-in functions?


Python provides many built-in functions to perform common tasks. Some of the most commonly used built-in functions include:

  • print(): Outputs data to the console.
  • len(): Returns the length of an object (e.g., list, string).
  • max(), min(): Returns the largest and smallest item from a collection.
  • sum(): Returns the sum of elements in an iterable.
  • range(): Generates a sequence of numbers.
  • abs(): Returns the absolute value of a number.
  • sorted(): Returns a sorted list.
  • type(): Returns the type of an object. Example:
    nums = [1, 2, 3, 4]
    print(sum(nums))  # Output: 10
    print(sorted(nums))  # Output: [1, 2, 3, 4]
    

     

50) What is the map() function in Python?


The map() function in Python is used to apply a function to all items in an iterable (like a list or tuple). It returns a map object, which is an iterator, and you can convert it to a list using list(). Example:

numbers = [1, 2, 3]
squares = map(lambda x: x ** 2, numbers)
print(list(squares))  # Output: [1, 4, 9]

 

51) What is the filter() function in Python?


The filter() function in Python is used to filter elements from an iterable based on a given function that returns a boolean value (True or False). Only the elements for which the function returns True are included in the result. The filter() function returns an iterator, which can be converted to a list using list(). Example:

numbers = [1, 2, 3, 4, 5, 6]
even_numbers = filter(lambda x: x % 2 == 0, numbers)
print(list(even_numbers))  # Output: [2, 4, 6]

 

52) What is the reduce() function in Python?


The reduce() function from the functools module in Python is used to apply a binary function (a function that takes two arguments) cumulatively to the items of an iterable. It reduces the iterable to a single value. Example:

from functools import reduce
numbers = [1, 2, 3, 4]
product = reduce(lambda x, y: x * y, numbers)
print(product)  # Output: 24

 

53) What is the difference between deepcopy() and copy() in Python?


  • copy(): Creates a shallow copy of an object. For compound objects (like lists of lists), it copies only the references to the nested objects, not the nested objects themselves.
  • deepcopy(): Creates a deep copy of an object, meaning it copies not just the object, but also all the objects contained within it (recursively). Example:
    import copy
    lst = [[1, 2], [3, 4]]
    shallow_copy = copy.copy(lst)
    deep_copy = copy.deepcopy(lst)
    
    lst[0][0] = 99
    print(shallow_copy)  # Output: [[99, 2], [3, 4]] (shared reference)
    print(deep_copy)  # Output: [[1, 2], [3, 4]] (independent copy)
    

     

54) What is a list comprehension in Python?


List comprehensions are a concise way to create lists. They allow you to apply an expression to each item in an iterable and optionally filter items using a condition, all in a single line of code. Example:

numbers = [1, 2, 3, 4]
squares = [x ** 2 for x in numbers]
print(squares)  # Output: [1, 4, 9, 16]

even_squares = [x ** 2 for x in numbers if x % 2 == 0]
print(even_squares)  # Output: [4, 16]

 

55) What is the enumerate() function in Python?


The enumerate() function in Python adds a counter to an iterable and returns an enumerate object, which can be converted into a list or looped over to get both the index and the value of each element. Example:

fruits = ["apple", "banana", "cherry"]
for index, fruit in enumerate(fruits):
    print(index, fruit)
# Output: 
# 0 apple
# 1 banana
# 2 cherry

 

56) What is the zip() function in Python?


The zip() function takes two or more iterables and aggregates them into tuples, where the first elements of each iterable are paired together, the second elements are paired together, and so on. Example:

names = ["Alice", "Bob", "Charlie"]
ages = [24, 30, 18]
zipped = zip(names, ages)
print(list(zipped))  # Output: [('Alice', 24), ('Bob', 30), ('Charlie', 18)]

 

57) What is the difference between == and is in Python?


  • ==: Checks for value equality. It returns True if the values of the two objects are the same.
  • is: Checks for identity equality. It returns True if the two objects are the same in memory (i.e., they refer to the same object). Example:
    a = [1, 2, 3]
    b = [1, 2, 3]
    print(a == b)  # Output: True (values are equal)
    print(a is b)  # Output: False (they are two different objects)
    

     

58) What is slicing in Python?


Slicing is a way to access a subset of elements from an iterable (like a list, tuple, or string) using the syntax [start:stop:step]. It allows you to extract parts of sequences. Example:

lst = [0, 1, 2, 3, 4, 5]
print(lst[1:4])  # Output: [1, 2, 3] (elements from index 1 to 3)
print(lst[:3])   # Output: [0, 1, 2] (elements from the start to index 2)
print(lst[::2])  # Output: [0, 2, 4] (every second element)

 

59) What is the all() function in Python?


The all() function returns True if all elements in an iterable are True (or if the iterable is empty). It short-circuits as soon as it finds a False value. Example:

lst = [True, True, False]
print(all(lst))  # Output: False (since one element is False)

lst2 = [True, True]
print(all(lst2))  # Output: True

 

60) What is the any() function in Python?


The any() function returns True if at least one element in an iterable is True. If the iterable is empty or all elements are False, it returns False. Example:

lst = [False, False, True]
print(any(lst))  # Output: True (since at least one element is True)

lst2 = [False, False]
print(any(lst2))  # Output: False

 

61) What are *args and **kwargs in Python?


  • *args: Allows you to pass a variable number of non-keyword arguments to a function. Inside the function, args is treated as a tuple.
  • **kwargs: Allows you to pass a variable number of keyword arguments to a function. Inside the function, kwargs is treated as a dictionary. Example:
    def example(*args, **kwargs):
        print(args)   # tuple of arguments
        print(kwargs) # dictionary of keyword arguments
    
    example(1, 2, 3, name="Alice", age=30)
    # Output:
    # (1, 2, 3)
    # {'name': 'Alice', 'age': 30}
    

     

62) What is the sorted() function in Python?


The sorted() function in Python is used to return a sorted version of an iterable (like a list, tuple, or string). It does not modify the original iterable but returns a new sorted list. Example:

lst = [4, 2, 1, 3]
sorted_lst = sorted(lst)
print(sorted_lst)  # Output: [1, 2, 3, 4]

 

63) What is the reversed() function in Python?


The reversed() function returns an iterator that yields the elements of an iterable in reverse order. It does not modify the original iterable. Example:

lst = [1, 2, 3]
reversed_lst = reversed(lst)
print(list(reversed_lst))  # Output: [3, 2, 1]

 

64) What are the differences between del, remove(), and pop() in Python lists?


  • del: Deletes an element at a specific index or an entire list. It doesn’t return the value of the element.
  • remove(): Removes the first occurrence of a value in a list. It raises an error if the value is not found.
  • pop(): Removes and returns an element at a specific index. If no index is provided, it removes and returns the last element. Example:
    lst = [1, 2, 3, 4]
    del lst[1]  # Deletes element at index 1
    print(lst)  # Output: [1, 3, 4]
    
    lst.remove(3)  # Removes the first occurrence of 3
    print(lst)  # Output: [1, 4]
    
    popped_item = lst.pop()  # Removes and returns the last element
    print(popped_item)  # Output: 4
    print(lst)  # Output: [1]
    

     

65) What is the difference between list and tuple in Python?


The main differences between list and tuple are:

  • Mutability: Lists are mutable, meaning you can change their contents after creation. Tuples are immutable, meaning once they are created, their contents cannot be modified.
  • Syntax: Lists are defined using square brackets [], while tuples are defined using parentheses (). Example:
    lst = [1, 2, 3]
    lst[0] = 10  # This is allowed because lists are mutable
    
    tup = (1, 2, 3)
    # tup[0] = 10  # This will raise an error because tuples are immutable
    

     

66) What is a regular expression (regex) in Python?


A regular expression (regex) in Python is a sequence of characters that forms a search pattern. Python provides the re module to work with regular expressions. It allows you to search, match, and manipulate strings using patterns. Example:

import re
text = "The rain in Spain"
match = re.search(r"\bS\w+", text)
print(match.group())  # Output: Spain

 

67) What is the purpose of the with statement in Python?


The with statement is used for resource management, specifically for simplifying the management of file handling or other resources that need to be properly acquired and released. It ensures that resources are automatically cleaned up after their use, even if an exception occurs. Example:

with open("file.txt", "r") as file:
    content = file.read()
    print(content)
# The file is automatically closed when the block is exited, whether or not an exception occurs.

 

68) How does Python handle memory management?


Python uses automatic memory management through reference counting and a garbage collector to reclaim memory used by objects that are no longer referenced. Python's memory management is built on the concept of object reference counting and uses a cyclic garbage collector to clean up memory. Example:

import gc
# You can manually trigger the garbage collector
gc.collect()

 

69) What is a frozenset in Python?


A frozenset in Python is an immutable version of a set. It is hashable, meaning it can be used as a key in a dictionary or added to another set. Once created, its elements cannot be modified. Example:

frozen = frozenset([1, 2, 3])
# frozen.add(4)  # This will raise an error because frozensets are immutable