Python Topic

Python Interview Questions For Freshers

Basic Level Questions

1. What is Python? What are its key features?

Answer: Python is a high-level, interpreted, and general-purpose programming language.

  • Key Features:

    • Easy to Learn: Simple syntax, readable like English.

    • Interpreted: Code is executed line by line, which makes debugging easy.

    • Dynamically Typed: You don't need to declare variable types.

    • Free and Open-Source: Anyone can use and contribute to it.

    • Large Standard Library: Comes with pre-built modules for many tasks.

    • Portable: Code written on one OS can run on another with little to no change.

2. How is memory managed in Python?

Answer: Python uses an automatic memory management mechanism known as Garbage Collection. The Python memory manager handles a private heap space where all objects are stored. The built-in gc module identifies and deletes objects that are no longer in use (i.e., objects with zero reference count) to free up memory.

3. What are the differences between a list and a tuple?

Answer:

Feature List Tuple
Mutability Mutable (can be changed) Immutable (cannot be changed)
Syntax Defined with square brackets [] Defined with parentheses ()
Performance Generally slower Generally faster
Use Case For collections of items that may change For collections of items that are constant

4. What are Python's key data structures?

Answer: The main built-in data structures are often called "Collections":

  • List: Ordered, mutable collection. [1, 2, 3]

  • Tuple: Ordered, immutable collection. (1, 2, 3)

  • Set: Unordered, mutable collection of unique elements. {1, 2, 3}

  • Dictionary (dict): Unordered collection of key-value pairs. {'key': 'value'}

5. What is PEP 8?

Answer: PEP 8 is the official Python Enhancement Proposal that provides style guidelines for writing readable and consistent Python code. It covers topics like indentation (use 4 spaces), line length (max 79 characters), naming conventions (e.g., snake_case for variables and functions), and more.


Intermediate Level Questions

6. Explain the difference between is and == in Python.

Answer:

  • == is a value equality operator. It checks if the values of two objects are the same.

  • is is an identity equality operator. It checks if both operands refer to the exact same object in memory (i.e., if their id() is the same).

Example:

python

list1 = [1, 2, 3]
list2 = [1, 2, 3]
list3 = list1

print(list1 == list2) # True (values are same)
print(list1 is list2) # False (different objects in memory)
print(list1 is list3) # True (same object)

7. What are list comprehensions? Give an example.

Answer: A list comprehension is a concise and readable way to create lists in a single line of code.
Syntax: [expression for item in iterable if condition]

Example: Create a list of squares for even numbers from 0 to 9.

python

# Traditional way
squares = []
for i in range(10):
    if i % 2 == 0:
        squares.append(i**2)

# Using List Comprehension
squares = [i**2 for i in range(10) if i % 2 == 0]
# Output: [0, 4, 16, 36, 64]

8. How do you handle exceptions in Python?

Answer: Exceptions are handled using try, except, else, and finally blocks.

python

try:
    # Code that might raise an exception
    result = 10 / 0
except ZeroDivisionError:
    # Handle a specific exception
    print("You can't divide by zero!")
except Exception as e:
    # Handle any other exception
    print(f"An error occurred: {e}")
else:
    # Code to run if no exception was raised
    print("Division successful!")
finally:
    # Code that always runs, used for cleanup (e.g., closing files)
    print("This always executes.")

9. What is the difference between append() and extend() for lists?

Answer:

  • append(): Adds its argument as a single element to the end of the list. The length of the list increases by one.

    python

    my_list = [1, 2, 3]
    my_list.append([4, 5])
    print(my_list) # Output: [1, 2, 3, [4, 5]]
  • extend(): Iterates over its argument and adds each element to the end of the list. The length of the list increases by the number of elements in the iterable.

    python

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

     

10. What are *args and **kwargs? When are they used?

Answer:

  • *args (Non-Keyword Arguments): Allows you to pass a variable number of positional arguments to a function. Inside the function, args is a tuple.

  • **kwargs (Keyword Arguments): Allows you to pass a variable number of keyword arguments (like name='Alice'). Inside the function, kwargs is a dictionary.

Example:

python

def my_function(a, *args, **kwargs):
    print(f"a: {a}")
    print(f"args: {args}") # Tuple of positional arguments
    print(f"kwargs: {kwargs}") # Dict of keyword arguments

my_function(10, 20, 30, 40, name="Bob", age=25)
# Output:
# a: 10
# args: (20, 30, 40)
# kwargs: {'name': 'Bob', 'age': 25}

11. What is the purpose of the __init__ method?

Answer: The __init__ method is a special constructor method in a Python class. It is automatically called when a new instance (object) of that class is created. Its primary purpose is to initialize the object's attributes.

Example:

python

class Dog:
    def __init__(self, name, breed):
        self.name = name   # 'self' refers to the current instance
        self.breed = breed

my_dog = Dog("Fido", "Labrador") # __init__ is called here
print(my_dog.name) # Output: Fido

12. Explain the difference between a shallow copy and a deep copy.

Answer:

  • Shallow Copy: Creates a new object but doesn't create copies of the objects inside the original object. Instead, it inserts references to the nested objects. Use copy.copy().

  • Deep Copy: Creates a new object and recursively adds copies of all objects found inside the original object. Use copy.deepcopy().

Example:

python

import copy

original = [[1, 2], [3, 4]]
shallow = copy.copy(original)
deep = copy.deepcopy(original)

original[0][0] = 99

print(original) # [[99, 2], [3, 4]]
print(shallow)  # [[99, 2], [3, 4]] (Nested list is changed!)
print(deep)     # [[1, 2], [3, 4]] (Unaffected by the change)

13. What are Python decorators?

Answer: A decorator is a powerful tool that allows you to modify or extend the behavior of a function or method without permanently changing its code. It is a function that takes another function as an argument and returns a new function.

Example: A simple decorator to measure execution time.

python

import time

def timer_decorator(func):
    def wrapper():
        start_time = time.time()
        func()
        end_time = time.time()
        print(f"Function took {end_time - start_time} seconds to run.")
    return wrapper

@timer_decorator
def my_slow_function():
    time.sleep(2)

my_slow_function()

14. What is the difference between a module and a package in Python?

Answer:

  • Module: A single Python file (with a .py extension) that contains Python code (functions, classes, variables). E.g., math.py is a module.

  • Package: A collection of modules in a directory. A package must contain a special file named __init__.py (which can be empty) to distinguish it from a regular directory.


Advanced Beginner Level Questions

15. What is the Global Interpreter Lock (GIL)?

Answer: The GIL is a mutex (a lock) in CPython (the standard Python implementation) that allows only one thread to execute in the interpreter at a time. This means that even on a multi-core processor, CPython cannot achieve true parallelism with threads for CPU-bound tasks. It was designed to make memory management thread-safe. To achieve true parallelism, the multiprocessing module is often used instead of threading.

16. How can you achieve multithreading and multiprocessing in Python?

Answer:

  • Multithreading: Use the threading module. It's best for I/O-bound tasks (like network requests, file operations) where the program is often waiting for external resources. Due to the GIL, it's not suitable for CPU-bound tasks.

  • Multiprocessing: Use the multiprocessing module. It creates separate Python processes, each with its own Python interpreter and memory space, thus bypassing the GIL. It's best for CPU-bound tasks that can be parallelized.

17. What are generators in Python? Why are they used?

Answer: Generators are a simple way to create iterators using a function with the yield keyword instead of return. They generate items one at a time and only when asked (lazy evaluation), which is memory efficient for large datasets.

Example:

python

def square_generator(n):
    for i in range(n):
        yield i ** 2  # 'yield' pauses the function

# Using the generator
my_gen = square_generator(5)
for num in my_gen:
    print(num) # Output: 0, 1, 4, 9, 16

18. What is the with statement used for? Give an example.

Answer: The with statement is used for resource management and exception handling. It simplifies the management of common resources like file streams by ensuring that clean-up code (like closing a file) is executed, even if an exception occurs. This concept is known as a context manager.

Example: File Handling

python

# Without 'with' (manual closing)
file = open('file.txt', 'r')
content = file.read()
file.close() # Must not forget to close!

# With 'with' (recommended)
with open('file.txt', 'r') as file:
    content = file.read()
# The file is automatically closed when the block is exited.

19. Explain the self keyword in Python.

Answer: self represents the instance of the class. It is the first parameter of any instance method in a class. Through the self keyword, we can access the attributes and methods of that class. It binds the attributes with the given arguments. While the word self is a convention, it is not a reserved keyword; you could use any other name, but it is highly discouraged.

20. What is the difference between a static method and a class method?

Answer:

Feature Static Method (@staticmethod) Class Method (@classmethod)
Decorator @staticmethod @classmethod
Parameter No mandatory first parameter. First parameter is always cls (the class itself).
Access to Cannot access or modify class state. Can access and modify the class state via cls.
Callable From Can be called on an instance or the class. Can be called on an instance or the class.
Use Case Utility function that logically belongs to the class. Factory method to create instances, or method that operates on the class.

Example:

python

class MyClass:
    class_attr = 10

    @classmethod
    def class_method(cls):
        print(f"Class attribute is {cls.class_attr}")

    @staticmethod
    def static_method():
        print("I am independent of the class.")

MyClass.class_method() # Output: Class attribute is 10
MyClass.static_method() # Output: I am independent of the class.

Good luck with your interview! Remember to practice writing code by hand and explaining your thought process clearly.

 

 

Comments (0)

No comments yet. Be the first to comment!

LecturreAI Assistant

Hello! I'm LecturreAI

What would you like to learn today?