Python interview questions and answer for freshers

  1) What is the difference between list and tuples in Python?

Both lists and tuples are used to store multiple items in a single variable, but they differ in their functionality and behavior. Below is a simple explanation with easy-to-understand examples.
Feature List Tuple
Mutability Mutable Immutable
Syntax [ ] ( )
Performance Slower Faster
Memory Usage More Less
Methods Many Limited
Use Case Dynamic Data Fixed Data
Hashable No(can't be used for
dictionary keys)
          Yes
       (It can be used for dictionary keys)
 
Here's a quick example:

# List example
fruits = ['apple', 'banana', 'cherry']
fruits.append('date')  # You can modify lists
print(fruits)

# Tuple example
coordinates = (10, 20)
# coordinates[0] = 30  # This would raise an error because tuples are immutable
print(coordinates)
What is the difference between list and tuples in Python?

2. How is Python an interpreted language?

Answer:
Python code is executed line-by-line by the Python interpreter, without requiring prior compilation into machine-level code. This makes Python platform-independent.

Python an interpreted language

3. How is memory managed in Python?

Answer:
Memory management in Python is handled by:

  • Reference Counting: Tracks the number of references to an object.
  • Garbage Collection: Reclaims memory occupied by objects with no references.
  • Private Heap: Stores all Python objects and data structures.
How is memory managed in Python?
When you assign an object to a variable, the reference to that object is stored in the stack. For example, in y = [1, 2, 3], y is y reference (pointer) to a list object stored in the heap.

def example_function():
    x = 10           # Stack memory: Integer '10' is stored directly in the stack
    y = [1, 2, 3]    # Heap memory: List object [1, 2, 3] is stored in the heap
    z = x + 1        # Stack memory: Integer result of x + 1, stored in the stack
    # Both 'x' and 'z' are stack variables (with values), while 'y' is a reference in the stack pointing to the list in the heap

example_function()
        

4. What are Python namespaces?

Answer:
A namespace is a container that holds names (variables, functions, etc.) and maps them to objects. Types:

  • Local Namespace: Within a function.
  • Global Namespace: At the module level.
  • Built-in Namespace: Provided by Python (e.g., print, len).
What are Python namespaces?

example:

# Global Namespace
x = 10  # Global variable

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

# Accessing Built-in Namespace
print("Built-in function:", len([1, 2, 3]))  # Using a built-in function (len)

# Calling the function to demonstrate Local and Global namespaces
my_function()

# Accessing Global variable outside the function
print("Global variable x outside function:", x)
        
        
        

Built-in function: 3
Inside function:
Global variable x: 10
Local variable y: 5
Global variable x outside function: 10

5. What are decorators in Python?

Answer:
Decorators modify the behavior of a function or method. They are defined using the @decorator_name syntax.

What are decorators in Python?
example:

# Decorator function
def our_decorator(func):
    def wrapper():
        print("Before function call")  # Pre-processing
        func()  # Call the original function
        print("After function call")   # Post-processing
    return wrapper

# Function to decorate
@our_decorator
def say_hello():
    print("Hello!")

# Calling the decorated function
say_hello()
            
            
output

Before function call
Hello!
After function call
          

  • our_decorator: A decorator function that takes another function (func) as an argument. It defines a wrapper function that enhances the behavior of the original function by adding some logic before and after the function call.
  • say_hello: This is the original function that prints "Hello!". The @our_decorator syntax is shorthand for applying the decorator to this function.
  • When say_hello() is called, it actually calls the wrapper() function, which adds additional behavior before and after the original function is executed.
  • 6. What are Dict and List comprehensions?

    Answer:
    They are concise ways to create dictionaries and lists.

  • What are Dict and List comprehensions?
    example:
    
    # List comprehension to create a list of squares
    squares = [x**2 for x in range(5)]
    print(squares)  # Output: [0, 1, 4, 9, 16]
              
              
    
    # Dictionary comprehension to create a dictionary of squares
    square_dict = {x: x**2 for x in range(5)}
    print(square_dict)  # Output: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
              
     

    7. What is the difference between .py and .pyc files?

    Answer:

    • .py: Source code file.
    • .pyc: Compiled bytecode file, generated when the code is executed, for faster loading.

    What is the difference between .py and .pyc files
  • Source File (.py): This is the original Python file, written in plain text. It contains human-readable code and needs to be interpreted by Python.
  • Compiled File (.pyc): When Python executes a .py file, it compiles it into bytecode, which is saved as .pyc (Python Compiled) files. These are used to make subsequent executions faster because Python doesn't need to recompile the code.
  • Bytecode is platform-independent. This means that the .pyc file can be run on any system where Python is installed without the need to recompile the source code.

  • 8. What is slicing in Python?

    Answer:
    Slicing extracts parts of sequences like lists, strings, or tuples.

    What is slicing in Python?

    example:

    
    # Example list
    my_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    
    # Slicing from index 2 to 5
    sliced_list = my_list[2:6]
    print(sliced_list)  # Output: [2, 3, 4, 5]
          
          
    
    # Example string
    my_string = "Python Slicing"
    
    # Slicing from index 0 to 5
    sliced_string = my_string[0:6]
    print(sliced_string)  # Output: "Python" 
             

    Slicing Syntax:

    • start:end:step:
      • start: The index to begin the slice (inclusive).
      • end: The index to end the slice (exclusive).
      • step (optional): The step size between elements in the slice.

    9. What are local variables and global variables in Python?

    Answer:

    • Local Variables: Declared inside functions; accessible only within that function.
    • Global Variables: Declared outside all functions; accessible throughout the script.
    What are local variables and global variables in Python?

    Example:
    
    # Global variable
    x = 10
    
    def my_function():
        # Local variable
        y = 5
        print("Local variable y:", y)
        
        # Access global variable
        global x
        x += 1  # Modify global variable
        print("Modified global variable x:", x)
    
    my_function()
    print("Global variable x after modification:", x)
          
          
    Output:
    
    Local variable y: 5
    Modified global variable x: 11
    Global variable x after modification: 11          
              

    Key Points:

    • Global variables can be accessed and modified anywhere if declared as global inside a function.
    • Local variables are restricted to the function in which they are defined and cannot be accessed outside.

    10. What is the difference between Python Arrays and lists?

    Answer:

    • Arrays: Homogeneous data types; require the array module.
    • Lists: Heterogeneous data types; built-in.
    What is the difference between Python Arrays and lists?

    Example:
    
    # Python List Example
    my_list = [1, "text", 3.14]
    print(my_list)
    
    # Python Array Example
    import array
    my_array = array.array('i', [1, 2, 3])  # 'i' indicates integer array
    print(my_array)            
                

    11. What is __init__?

    Answer:
    __init__ is a special method in Python called a constructor. It initializes object attributes when the object is created.

    Example:

    
    # Define a class
    class Person:
        # The __init__ method is called when an object is created
        def __init__(self, name, age):
            self.name = name  # Set the name
            self.age = age    # Set the age
    
        # Display the person's information
        def display_info(self):
            print(f"Name: {self.name}, Age: {self.age}")
    
    # Create an object of the Person class
    person1 = Person("@PythonBeeTelugu", 30)
    
    # Show the person's info
    person1.display_info()
              
              
    
    Name: @PythonBeeTelugu, Age: 30
    

    Explanation:

    • The __init__ method is a special method in Python that runs when you create an object.
    • It is used to set the initial values of the object's attributes (name and age).
    • In the example, when person1 is created, name is set to "@PythonBeeTelugu" and age is set to 30.
    • The display_info method shows these values.

    12. What is a lambda function?

    Answer:
    A lambda function is an anonymous function defined using the lambda keyword.

    What is a lambda function?

  • Syntax: The syntax is lambda arguments: expression. For example, lambda x, y: x + y adds two numbers and returns the result.
  • Use Case: Lambda functions are useful when you need a quick function for operations like sorting, mapping, or reducing in code.

  • Example:
    
    # Define a lambda function that adds two numbers
    simple_lambda = lambda x, y: x + y
    
    # Use the lambda function
    result = simple_lambda(3, 5)
    
    # Print the result
    print(result)  # Output: 8
    

    13. What is self in Python?

    Answer:
    self represents the instance of the class and is used to access attributes and methods.

    What is self in Python?

    Example:

    
    class PythonClass:
        def __init__(self, name):
            # `self` refers to the current instance of the class
            self.name = name
        
        def say_hello(self):
            # `self.name` accesses the instance variable
            return f"Hello, {self.name}!"
    
    # Creating an instance of the class
    instance = PythonClass("Ravi")
    
    # Calling the method using the instance
    print(instance.say_hello())  # Output: Hello, Ravi!
    
    

    Explanation:

    1. self in __init__:

      • When you create an object (instance = PythonClass("Ravi")), self refers to this specific object.
      • self.name = name sets the instance variable name to "Ravi".
    2. Accessing Instance Variables:

      • Inside the say_hello method, self.name is used to access the name variable of the instance.
    3. Using the Instance:

      • The instance (instance) calls the method say_hello. Python automatically passes the instance as the first argument (self) to the method.

    14. What is pickling and unpickling?

    Answer:

    • Pickling: Serializing Python objects into a byte stream.
    • Unpickling: Deserializing the byte stream back to Python objects.
    what is pickling and unpickling in python?
    • Pickling:

      • Converts a Python object into a byte stream (serialized format).
      • Can store the byte stream in a file or send it over a network.
      • Achieved using pickle.dump(obj, file) or pickle.dumps(obj).
    • Unpickling:

      • Reconstructs the original Python object from the byte stream.
      • Achieved using pickle.load(file) or pickle.loads(data).
    Example:
    
    import pickle
    
    # Python object to be pickled
    data = {'name': 'Ravi', 'age': 28, 'skills': ['Python', 'FastAPI']}
    
    # Pickling: Save object to a file
    with open('data.pkl', 'wb') as file:
        pickle.dump(data, file)
    print("Data has been pickled and saved to data.pkl")
    
    # Unpickling: Load object from a file
    with open('data.pkl', 'rb') as file:
        loaded_data = pickle.load(file)
    print("Data after unpickling:", loaded_data)
    

    15. What are docstrings in Python?

    Answer:
    Docstrings are documentation strings used to explain the purpose of a function, class, or module.

    What are What are docstrings in Python??

    Example:

    
    """This is a module-level docstring."""
    def add(a, b):
        """Returns the sum of a and b."""
        return a + b
    
    class Calculator:
        """A class to perform basic calculations."""
        
        def multiply(self, a, b):
            """Returns the product of a and b."""
            return a * b
    
    # Accessing docstrings
    print(add.__doc__)         # Output: Returns the sum of a and b.
    print(Calculator.__doc__)  # Output: A class to perform basic calculations.
    help(add)                  # Shows the function's docstring
    help(Calculator)           # Shows the class's docstring and its methods
    
  • Docstrings provide inline documentation and are critical for maintainability.
  • Use help() or __doc__ to view docstrings at runtime.
  • Comments