Python Interview Questions for Freshers

Top 50 Python Interview Questions and Answers for Freshers

This Python Interview Questions and Answers guide helps new graduates and entry-level professionals prepare comprehensively for programming job interviews with carefully curated questions and detailed answers specifically designed for freshers entering the competitive software development field.

We included fundamental Python interview questions covering core programming concepts, essential data structures, basic algorithms, and practical coding exercises that entry-level positions consistently evaluate during technical assessments.

The Python Interview Questions guide covers everything from basic syntax, variables, and data types to more complex topics like functions, loops, object-oriented programming principles, and error handling that companies rigorously test beginners on during multiple interview rounds.

We are providing the structured preparation framework necessary to excel in technical interviews and secure your first Python developer position in today’s demanding job market.

Basic Python Interview Questions and Answers for Freshers

Answer: Python is a high-level, interpreted programming language known for its simplicity and readability. It uses clear syntax, making it easy to learn and understand.

Key reasons for popularity:

  • Simple and readable syntax, resembling plain English.
  • Versatile, used in web development, data science, automation, and more.
  • Large standard library and community support for learning resources.

Example:

print("Hello, Python!")  # Simple syntax to print a message

Key points:

  • Ideal for beginners due to its straightforward syntax.
  • Supports multiple programming paradigms (e.g., procedural, object-oriented).
  • Widely used in industry, increasing job opportunities.

Que 2. What are the differences between Python 2 and Python 3?

Answer: Python 2 and Python 3 are two major versions of Python, with Python 3 being the current standard.

FeaturePython 2Python 3
Print Statementprint “Hello” (no parentheses)print(“Hello”) (requires parentheses)
Integer Division5 / 2 returns 25 / 2 returns 2.5
Unicode SupportLimited, uses ASCII by defaultNative Unicode support
Support StatusEnd-of-life in 2020Actively maintained

Example:

# Python 3
print(5 / 2)  # Outputs: 2.5

Key points:

  • Python 3 is recommended for freshers as it is actively supported.
  • Most libraries and frameworks are compatible with Python 3.
  • Understanding the differences helps when working with legacy code.

Que 3. How do you define a variable in Python, and what are dynamic typing?

Answer: In Python, a variable is defined by assigning a value to a name using the = operator. Python uses dynamic typing, meaning you don’t need to declare the variable’s type explicitly; it is inferred at runtime.

Example:

name = "Alice"  # String variable
age = 25        # Integer variable
height = 5.6    # Float variable

Key points:

  • Dynamic typing allows flexibility but requires careful handling to avoid type errors.
  • Variables can change types during execution (e.g., age = “twenty-five”).
  • Simple for freshers to start coding without type declarations.

Que 4. What are the basic data types in Python?

Answer: Python has several built-in data types used to store different kinds of data.

Basic data types:

  • Integer (int): Whole numbers (e.g., 5, -3)
  • Float (float): Decimal numbers (e.g., 3.14, -0.5)
  • String (str): Text data (e.g., “Hello”)
  • Boolean (bool): True or False
  • List: Ordered, mutable collection (e.g., [1, 2, 3])
  • Tuple: Ordered, immutable collection (e.g., (1, 2, 3))
  • Dictionary: Key-value pairs (e.g., {“name”: “Alice”, “age”: 25})
  • Set: Unordered collection of unique elements (e.g., {1, 2, 3})

Example:

x = 10          # int
y = 3.14        # float
name = "Bob"    # str
is_student = True  # bool

Key points:

  • Each type serves specific purposes, like lists for collections or dictionaries for mappings.
  • Freshers should understand type usage for basic programming tasks.
  • Use type() function to check a variable’s type.

Que 5. How do you write comments in Python, and why are they important?

Answer: Comments in Python are used to explain code, making it easier to understand and maintain. They are ignored by the interpreter.

Types of comments:

  • Single-line: Starts with #.
  • Multi-line: Uses triple quotes (”’ or “””) for documentation strings.

Example:

# This is a single-line comment
x = 10  # Assigning 10 to x

"""
This is a multi-line comment
used for longer explanations
"""

Key points:

  • Comments improve code readability for freshers and teams.
  • Useful for documenting code logic or purpose.
  • Multi-line comments are often used as docstrings for functions or classes.

Que 6. What is the difference between a list and a tuple in Python?

Answer: Lists and tuples are both sequence data types in Python, but they differ in mutability and usage.

FeatureListTuple
MutabilityMutable (can be changed)Immutable (cannot be changed)
SyntaxDefined with [] (e.g., [1, 2])Defined with () (e.g., (1, 2))
PerformanceSlower due to mutabilityFaster due to immutability
Use CaseDynamic data modificationFixed data, like constants

Example:

my_list = [1, 2, 3]
my_list[0] = 4  # Modifies list: [4, 2, 3]

my_tuple = (1, 2, 3)
# my_tuple[0] = 4  # Error: tuples are immutable

Key points:

  • Use lists for data that changes, tuples for data that remains constant.
  • Tuples are more memory-efficient.
  • Helps freshers choose the right data structure.

Que 7. How do you define and call a function in Python?

Answer: A function in Python is defined using the def keyword, followed by the function name, parameters, and a block of code. It is called by using the function name with arguments.

Example:

# Define a function
def greet(name):
    return f"Hello, {name}!"

# Call the function
message = greet("Alice")
print(message)  # Outputs: Hello, Alice!

Key points:

  • Functions promote code reuse and modularity.
  • Parameters are optional; functions can return values or None.
  • Easy for freshers to create reusable code blocks.

Que 8. What are Python’s conditional statements, and how do you use them?

Answer: Python’s conditional statements (if, elif, else) control the flow of execution based on conditions.

Example:

age = 18
if age >= 18:
    print("You are an adult")
elif age >= 13:
    print("You are a teenager")
else:
    print("You are a child")

Key points:

  • Conditions evaluate to True or False.
  • elif allows multiple conditions; else handles the default case.
  • Simple for freshers to implement decision-making logic.

Que 9. How do you use loops in Python, and what is the difference between for and while loops?

Answer: Python supports for and while loops to execute code repeatedly.

  • for loop: Iterates over a sequence (e.g., list, range).
  • while loop: Repeats as long as a condition is True.

Example:

# for loop
for i in range(5):
    print(i)  # Outputs: 0, 1, 2, 3, 4

# while loop
count = 0
while count < 5:
    print(count)
    count += 1  # Outputs: 0, 1, 2, 3, 4

Key points:

  • Use for loops for known iteration counts; while loops for condition-based repetition.
  • break and continue control loop execution.
  • Easy for freshers to iterate over data or repeat tasks.

Que 10. What is a dictionary in Python, and how do you access its elements?

Answer: A dictionary in Python is a collection of key-value pairs, where keys are unique and used to access values. It is defined using curly braces {}.

Example:

student = {"name": "Alice", "age": 20, "grade": "A"}
print(student["name"])  # Outputs: Alice
student["age"] = 21    # Updates value
print(student)         # Outputs: {'name': 'Alice', 'age': 21, 'grade': 'A'}

Key points:

  • Keys must be immutable (e.g., strings, numbers); values can be any type.
  • Access values using square brackets or .get() (safer, avoids KeyError).
  • Useful for freshers to store and retrieve structured data.

Que 11. How do you handle exceptions in Python using try-except?

Answer: Python’s try-except block handles exceptions (errors) to prevent program crashes and provide graceful error handling.

Example:

try:
    result = 10 / 0
except ZeroDivisionError:
    print("Cannot divide by zero!")
else:
    print("Result:", result)
finally:
    print("This always executes")

Key points:

  • try: Contains code that might raise an exception.
  • except: Handles specific or general exceptions.
  • else: Runs if no exception occurs; finally: Always runs.
  • Helps freshers write robust code that handles errors.

Que 12. What is the purpose of the import statement in Python, and how do you use it?

Answer: The import statement in Python allows you to use functions, classes, or variables from modules (built-in or external) in your program.

Example:

import math
print(math.sqrt(16))  # Outputs: 4.0

from random import randint
print(randint(1, 10))  # Outputs: Random number between 1 and 10

Key points:

  • import module: Imports the entire module.
  • from module import name: Imports specific items.
  • Simplifies access to Python’s standard library for freshers.

Que 13. How do you create and use a list comprehension in Python?

Answer: List comprehension in Python provides a concise way to create lists by applying an expression to each item in an iterable, optionally with a condition.

Example:

# Create a list of squares for numbers 1 to 5
squares = [x**2 for x in range(1, 6)]
print(squares)  # Outputs: [1, 4, 9, 16, 25]

# Filter even numbers
evens = [x for x in range(10) if x % 2 == 0]
print(evens)  # Outputs: [0, 2, 4, 6, 8]

Key points:

  • Syntax: [expression for item in iterable if condition]
  • Reduces code compared to traditional loops.
  • Easy for freshers to create lists efficiently.

Que 14. What is the difference between append() and extend() methods in a Python list?

Answer: The append() and extend() methods modify a Python list but differ in how they add elements.

MethodDescriptionExample Output
append()Adds a single element to the end[1, 2, [3, 4]]
extend()Adds each element of an iterable[1, 2, 3, 4]

Example:

my_list = [1, 2]
my_list.append([3, 4])
print(my_list)  # Outputs: [1, 2, [3, 4]]

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

Key points:

  • Use append() to add one item (including lists); extend() to add multiple items.
  • Helps freshers manipulate lists correctly.
  • Avoids nested lists when extending iterables.

Que 15. How do you read and write files in Python?

Answer: Python provides built-in functions to read and write files using the open() function with appropriate modes (e.g., ‘r’ for reading, ‘w’ for writing).

Example:

# Writing to a file
with open('example.txt', 'w') as file:
    file.write("Hello, Python!")

# Reading from a file
with open('example.txt', 'r') as file:
    content = file.read()
    print(content)  # Outputs: Hello, Python!

Key points:

  • with statement ensures the file is closed automatically.
  • Modes: ‘r’ (read), ‘w’ (write), ‘a’ (append), ‘r+’ (read/write).
  • Simple for freshers to perform basic file operations.

Que 16. What is the difference between a set and a list in Python?

Answer: A set and a list in Python are both collections, but they differ in their properties and use cases.

FeatureListSet
StructureOrdered, allows duplicatesUnordered, no duplicates
SyntaxDefined with [] (e.g., [1, 2, 2])Defined with {} or set() (e.g., {1, 2})
MutabilityMutableMutable
Use CaseOrdered data with duplicatesUnique elements, set operations

Example:

my_list = [1, 2, 2, 3]
my_set = {1, 2, 2, 3}
print(my_list)  # Outputs: [1, 2, 2, 3]
print(my_set)   # Outputs: {1, 2, 3}

Key points:

  • Sets automatically remove duplicates, useful for unique data.
  • Lists maintain order and allow duplicates, ideal for sequences.
  • Helps freshers choose the right collection for their needs.

Que 17. How do you use the len() function in Python, and what types of objects can it be applied to?

Answer: The len() function in Python returns the number of items in an object, such as a string, list, tuple, dictionary, or set.

Example:

my_string = "Hello"
my_list = [1, 2, 3]
my_dict = {"a": 1, "b": 2}

print(len(my_string))  # Outputs: 5 (characters)
print(len(my_list))    # Outputs: 3 (elements)
print(len(my_dict))    # Outputs: 2 (key-value pairs)

Key points:

  • Works with any sequence (string, list, tuple) or collection (dictionary, set).
  • Simple for freshers to check the size of data structures.
  • Raises TypeError for unsupported types (e.g., integers).

Que 18. What are Python’s string methods, and how can you use them to manipulate strings?

Answer: Python strings provide built-in methods to manipulate text, such as changing case, splitting, or replacing substrings.

Common methods:

  • upper(): Converts to uppercase.
  • lower(): Converts to lowercase.
  • strip(): Removes leading/trailing whitespace.
  • replace(): Replaces a substring.
  • split(): Splits a string into a list.

Example:

text = "  Hello, Python!  "
print(text.upper())        # Outputs: HELLO, PYTHON!
print(text.strip())        # Outputs: Hello, Python!
print(text.replace("Python", "World"))  # Outputs:   Hello, World!  
print(text.split(","))     # Outputs: ['  Hello', ' Python!  ']

Key points:

  • Strings are immutable, so methods return new strings.
  • Easy for freshers to format and process text data.
  • Chaining methods (e.g., text.strip().upper()) is common.

Que 19. How do you use the range() function in Python, and what is it commonly used for?

Answer: The range() function in Python generates a sequence of numbers, commonly used in for loops to iterate a specific number of times.

Syntax: range(start, stop, step)

  • start: Starting number (default 0).
  • stop: End number (exclusive).
  • step: Increment (default 1).

Example:

for i in range(5):  # Generates 0, 1, 2, 3, 4
    print(i)

for i in range(2, 7, 2):  # Generates 2, 4, 6
    print(i)

Key points:

  • Ideal for looping a fixed number of times.
  • Memory-efficient as it generates numbers on demand.
  • Helps freshers write simple loops for iteration.

Que 20. What is a Python module, and how do you create and use one?

Answer: A Python module is a file containing Python code (e.g., functions, classes) that can be imported and reused in other programs.

Creating a module:

  • Save code in a .py file (e.g., mymodule.py).
  • Import it using the import statement.

Example:

# mymodule.py
def greet(name):
    return f"Hello, {name}!"

# main.py
import mymodule
print(mymodule.greet("Alice"))  # Outputs: Hello, Alice!

Key points:

  • Modules promote code reuse and organization.
  • Freshers can create modules to modularize their code.
  • Use import module or from module import name for specific imports.

Que 21. How do you use the if name == “main“: block in Python?

Answer: The if name == “main“: block in Python checks if a module is being run directly or imported, allowing code to execute only when the script is run directly.

Example:

def add(a, b):
    return a + b

if __name__ == "__main__":
    print(add(2, 3))  # Outputs: 5 (runs only when script is executed directly)

Key points:

  • Prevents code from running when the module is imported.
  • Useful for testing or running main program logic.
  • Helps freshers understand script vs. module behavior.

Que 22. What are Python’s comparison operators, and how are they used?

Answer: Python’s comparison operators compare values and return a boolean (True or False).

Operators:

  • ==: Equal to
  • !=: Not equal to
  • <: Less than
  • : Greater than
  • <=: Less than or equal to
  • =: Greater than or equal to

Example:

a = 5
b = 3
print(a == b)  # Outputs: False
print(a > b)   # Outputs: True
print(a <= 5)  # Outputs: True

Key points:

  • Used in conditional statements and loops.
  • Simple for freshers to implement decision logic.
  • Can compare numbers, strings, and other types.

Que 23. How do you use the slice notation in Python to extract parts of a sequence?

Answer: Slice notation in Python extracts parts of a sequence (e.g., string, list, tuple) using the syntax sequence[start:stop:step].

Example:

text = "Hello, Python"
print(text[0:5])      # Outputs: Hello
print(text[7:])       # Outputs: Python
print(text[::2])      # Outputs: Hlo yhn (every second character)

Key points:

  • start: Starting index (inclusive, default 0).
  • stop: Ending index (exclusive).
  • step: Increment (default 1).
  • Easy for freshers to manipulate sequences.

Que 24. What is the purpose of the global keyword in Python, and how is it used?

Answer: The global keyword in Python allows a function to modify a global variable, rather than creating a local variable with the same name.

Example:

count = 0

def increment():
    global count  # Declare count as global
    count += 1

increment()
print(count)  # Outputs: 1

Key points:

  • Without global, a function creates a local variable.
  • Use sparingly to avoid complex code.
  • Helps freshers understand variable scope.

Que 25. How do you use the join() method in Python to combine a list of strings?

Answer: The join() method in Python combines a list of strings into a single string, using a specified separator.

Example:

words = ["Hello", "Python", "World"]
result = " ".join(words)
print(result)  # Outputs: Hello Python World

result = ",".join(words)
print(result)  # Outputs: Hello,Python,World

Key points:

  • Syntax: separator.join(list)
  • Efficient for combining strings compared to concatenation.
  • Useful for freshers formatting output or CSV data.
Top Python Interview Questions for Freshers

Advanced Python Interview Questions and Answers for Freshers

Que 26. What is the difference between a shallow copy and a deep copy in Python, and how do you create them?

Answer: In Python, a shallow copy creates a new object but references the same nested objects, while a deep copy creates a fully independent copy, including all nested objects.

FeatureShallow CopyDeep Copy
Nested ObjectsReferences original objectsCreates new copies of objects
Modification ImpactAffects nested objects in bothIndependent of original
Modulecopy.copy()copy.deepcopy()

Example:

import copy

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

shallow[0][0] = 4
print(original)  # Outputs: [[4, 2], 3]
print(shallow)   # Outputs: [[4, 2], 3]
print(deep)      # Outputs: [[1, 2], 3]

Key points:

  • Use shallow copy for simple structures, deep copy for nested objects.
  • Helps freshers avoid unintended modifications in complex data structures.
  • Requires the copy module.

Que 27. How do you define a class in Python, and what is the purpose of the init method?

Answer: A class in Python is defined using the class keyword, encapsulating data and behavior. The __init__ method is a constructor that initializes instance variables when an object is created.

Example:

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

    def introduce(self):
        return f"Hi, I'm {self.name}, {self.age} years old"

person = Person("Alice", 25)
print(person.introduce())  # Outputs: Hi, I'm Alice, 25 years old

Key points:

  • __init__ sets up object state with instance variables.
  • self refers to the instance, required in method definitions.
  • Classes introduce freshers to object-oriented programming (OOP).

Que 28. What are list comprehensions, and how can you use them with conditional logic?

Answer: List comprehensions in Python provide a concise way to create lists using a single line of code, often including conditional logic for filtering.

Example:

# List comprehension with condition
numbers = [1, 2, 3, 4, 5]
even_squares = [x**2 for x in numbers if x % 2 == 0]
print(even_squares)  # Outputs: [4, 16]

# Equivalent loop
even_squares = []
for x in numbers:
    if x % 2 == 0:
        even_squares.append(x**2)

Key points:

  • Syntax: [expression for item in iterable if condition]
  • Reduces code verbosity compared to loops.
  • Helps freshers write efficient, readable code.

Que 29. How does Python’s try-except-else-finally block work, and what is the role of each clause?

Answer: The try-except-else-finally block in Python handles exceptions to prevent crashes and ensure cleanup.

  • try: Contains code that might raise an exception.
  • except: Catches and handles specific exceptions.
  • else: Runs if no exception occurs in the try block.
  • finally: Always executes, regardless of exceptions.

Example:

try:
    result = 10 / 2
except ZeroDivisionError:
    print("Division by zero!")
else:
    print(f"Result: {result}")
finally:
    print("Cleanup done")
# Outputs: Result: 5.0
#         Cleanup done

Key points:

  • else avoids mixing success logic with exception handling.
  • finally is useful for resource cleanup (e.g., closing files).
  • Essential for freshers to write robust code.

Que 30. What are Python decorators, and how can you create a simple decorator?

Answer: Decorators in Python are functions that modify the behavior of another function or method, often used for logging, authentication, or timing.

Example:

def my_decorator(func):
    def wrapper():
        print("Before the function")
        func()
        print("After the function")
    return wrapper

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

say_hello()
# Outputs: Before the function
#         Hello!
#         After the function

Key points:

  • Decorators use the @ syntax to wrap functions.
  • Useful for adding reusable functionality without modifying code.
  • Accessible for freshers to enhance function behavior.

Que 31. How do you use the map() function in Python, and what is its purpose?

Answer: The map() function applies a given function to each item in an iterable, returning an iterator of results. It simplifies transforming data.

Example:

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

Key points:

  • Syntax: map(function, iterable)
  • More concise than loops for applying transformations.
  • Helps freshers process collections functionally.

Que 32. What is the purpose of the *args and **kwargs in Python function definitions?

Answer: *args and **kwargs allow functions to accept a variable number of arguments.

  • *args: Collects positional arguments into a tuple.
  • **kwargs: Collects keyword arguments into a dictionary.

Example:

def print_args(*args, **kwargs):
    print("Positional args:", args)
    print("Keyword args:", kwargs)

print_args(1, 2, name="Alice", age=25)
# Outputs: Positional args: (1, 2)
#         Keyword args: {'name': 'Alice', 'age': 25}

Key points:

  • *args handles extra positional arguments; **kwargs handles named arguments.
  • Useful for flexible function definitions.
  • Easy for freshers to create versatile functions.

Que 33. How do you use the filter() function in Python, and what is its purpose?

Answer: The filter() function applies a predicate function to an iterable, returning an iterator of items for which the function returns True.

Example:

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

Key points:

  • Syntax: filter(function, iterable)
  • Filters data based on conditions, similar to list comprehension.
  • Helps freshers process data selectively.

Que 34. What is a Python generator, and how do you create one using the yield keyword?

Answer: A generator in Python is a function that produces values one at a time, using yield to pause execution and save state, making it memory-efficient for large datasets.

Example:

def count_up_to(n):
    for i in range(1, n + 1):
        yield i

gen = count_up_to(3)
for num in gen:
    print(num)  # Outputs: 1, 2, 3

Key points:

  • Generators produce values lazily, saving memory.
  • yield returns a value and pauses the function.
  • Useful for freshers handling large or streamed data.

Que 35. How do you use the lambda function in Python, and what is its purpose?

Answer: A lambda function in Python is an anonymous, single-expression function used for short, simple operations.

Example:

# Lambda to add two numbers
add = lambda x, y: x + y
print(add(2, 3))  # Outputs: 5

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

Key points:

  • Syntax: lambda arguments: expression
  • Used in functional programming (e.g., with map(), filter()).
  • Simplifies small tasks for freshers.

Que 36. What is the difference between global and nonlocal keywords in Python?

Answer: The global and nonlocal keywords in Python control variable scope in nested functions.

  • global: Allows modification of a global variable.
  • nonlocal: Allows modification of a variable in an enclosing (non-global) scope.

Example:

x = 0
def outer():
    x = 1
    def inner():
        nonlocal x
        x = 2
    inner()
    print(x)  # Outputs: 2

outer()

Key points:

  • global accesses variables at the module level; nonlocal accesses variables in enclosing functions.
  • Helps freshers manage variable scope in nested functions.
  • Use cautiously to avoid complex code.

Que 37. How do you work with dictionaries in Python, including common methods like get() and items()?

Answer: Dictionaries in Python store key-value pairs and provide methods like get() and items() for accessing and manipulating data.

Example:

my_dict = {"name": "Alice", "age": 25}
print(my_dict.get("name"))  # Outputs: Alice
print(my_dict.get("grade", "N/A"))  # Outputs: N/A (default value)

for key, value in my_dict.items():
    print(f"{key}: {value}")  # Outputs: name: Alice, age: 25

Key points:

  • get(key, default) safely retrieves values, avoiding KeyError.
  • items() returns key-value pairs for iteration.
  • Useful for freshers handling structured data.

Que 38. What is the purpose of the str and repr methods in a Python class?

Answer: The __str__ and __repr__ methods define string representations of a Python object.

  • str: Returns a human-readable string, used by print().
  • repr: Returns a detailed string, often for debugging, used by repr().

Example:

class Person:
    def __init__(self, name):
        self.name = name
    
    def __str__(self):
        return f"Person: {self.name}"
    
    def __repr__(self):
        return f"Person(name='{self.name}')"

p = Person("Alice")
print(str(p))   # Outputs: Person: Alice
print(repr(p))  # Outputs: Person(name='Alice')

Key points:

  • __str__ is user-friendly; __repr__ is developer-friendly.
  • Helps freshers customize object representations.
  • __repr__ should ideally allow object recreation.

Que 39. How do you use the with statement in Python for resource management?

Answer: The with statement in Python ensures proper resource management (e.g., opening/closing files) by automatically handling setup and cleanup, even if an error occurs.

Example:

with open("example.txt", "w") as file:
    file.write("Hello, Python!")  # File is automatically closed

Key points:

  • Works with objects implementing __enter__ and __exit__ (context managers).
  • Prevents resource leaks, like unclosed files.
  • Simplifies file handling for freshers.

Que 40. What are Python’s built-in functions like sorted() and sum(), and how are they used?

Answer: Python’s built-in functions like sorted() and sum() perform common operations on iterables.

  • sorted(): Returns a sorted list from an iterable.
  • sum(): Calculates the sum of numbers in an iterable.

Example:

numbers = [3, 1, 4, 2]
sorted_numbers = sorted(numbers)
print(sorted_numbers)  # Outputs: [1, 2, 3, 4]
print(sum(numbers))    # Outputs: 10

Key points:

  • sorted() creates a new list; sort() modifies in place.
  • sum() works with numeric iterables.
  • Easy for freshers to perform common operations.

Que 41. How do you implement inheritance in Python, and what is the role of the super() function?

Answer: Inheritance in Python allows a class to inherit attributes and methods from a parent class. The super() function accesses parent class methods, often used in __init__.

Example:

class Animal:
    def __init__(self, name):
        self.name = name
    
    def speak(self):
        return "Sound"

class Dog(Animal):
    def __init__(self, name, breed):
        super().__init__(name)
        self.breed = breed
    
    def speak(self):
        return "Woof"

dog = Dog("Max", "Labrador")
print(dog.name)   # Outputs: Max
print(dog.speak())  # Outputs: Woof

Key points:

  • Inheritance promotes code reuse.
  • super() initializes parent class attributes.
  • Helps freshers understand OOP concepts.

Que 42. What is the purpose of the zip() function in Python, and how is it used?

Answer: The zip() function in Python combines multiple iterables into a single iterable of tuples, pairing elements by index.

Example:

names = ["Alice", "Bob"]
ages = [25, 30]
zipped = list(zip(names, ages))
print(zipped)  # Outputs: [('Alice', 25), ('Bob', 30)]

Key points:

  • Useful for iterating over multiple lists simultaneously.
  • Returns an iterator, often converted to a list or tuple.
  • Simplifies data pairing for freshers.

Que 43. How do you use the enumerate() function in Python, and what is its benefit?

Answer: The enumerate() function in Python adds an index to each item in an iterable, returning an iterator of tuples containing the index and value.

Example:

fruits = ["apple", "banana", "orange"]
for index, fruit in enumerate(fruits):
    print(f"{index}: {fruit}")
# Outputs: 0: apple
#         1: banana
#         2: orange

Key points:

  • Simplifies tracking indices in loops.
  • More readable than manual index counters.
  • Helps freshers iterate with indices efficiently.

Que 44. What are Python’s f-strings, and how do they improve string formatting?

Answer: F-strings (formatted string literals) in Python (introduced in Python 3.6) allow embedding expressions inside string literals using curly braces, improving readability and simplicity.

Example:

name = "Alice"
age = 25
print(f"My name is {name} and I'm {age} years old")
# Outputs: My name is Alice and I'm 25 years old

Key points:

  • Syntax: f"string {expression}"
  • More concise than .format() or % formatting.
  • Easy for freshers to format strings dynamically.

Que 45. How do you use the any() and all() functions in Python, and what are their use cases?

Answer: The any() and all() functions in Python evaluate iterables of boolean values.

  • any(): Returns True if at least one element is True.
  • all(): Returns True if all elements are True.

Example:

numbers = [1, 2, 3, 4]
print(any(x > 3 for x in numbers))  # Outputs: True
print(all(x > 0 for x in numbers))  # Outputs: True

Key points:

  • Useful for checking conditions in iterables.
  • Short-circuits evaluation for efficiency.
  • Helps freshers simplify boolean logic.

Que 46. What is the difference between init.py and a regular Python file?

Answer: The __init__.py file marks a directory as a Python package, allowing modules within it to be imported. A regular Python file contains executable code or definitions.

Featureinit.pyRegular Python File
PurposeDefines a packageContains code or definitions
LocationIn a package directoryAnywhere
ContentOften empty or initializationFunctions, classes, etc.

Example:

# mypackage/__init__.py (can be empty)

# mypackage/mymodule.py
def hello():
    return "Hello from module"

# main.py
from mypackage.mymodule import hello
print(hello())  # Outputs: Hello from module

Key points:

  • __init__.py enables package imports.
  • Can contain initialization code for the package.
  • Helps freshers organize larger projects.

Que 47. How do you use the sorted() function with a custom key in Python?

Answer: The sorted() function in Python sorts an iterable and accepts a key parameter to specify a custom sorting criterion.

Example:

words = ["apple", "Banana", "cherry"]
sorted_words = sorted(words, key=str.lower)
print(sorted_words)  # Outputs: ['apple', 'Banana', 'cherry']

# Sort by length
sorted_by_length = sorted(words, key=len)
print(sorted_by_length)  # Outputs: ['apple', 'cherry', 'Banana']

Key points:

  • key function is applied to each element for comparison.
  • Flexible for custom sorting (e.g., case-insensitive, length-based).
  • Useful for freshers to sort complex data.

Que 48. What is the purpose of the self parameter in Python class methods?

Answer: The self parameter in Python class methods refers to the instance of the class, allowing access to its attributes and methods.

Example:

class Car:
    def __init__(self, brand):
        self.brand = brand
    
    def drive(self):
        return f"{self.brand} is driving"

car = Car("Toyota")
print(car.drive())  # Outputs: Toyota is driving

Key points:

  • self is explicitly passed in method definitions but not when calling methods.
  • Enables instance-specific behavior in OOP.
  • Essential for freshers learning class-based programming.

Que 49. How do you use the collections module in Python, specifically defaultdict?

Answer: The collections module in Python provides specialized data structures. defaultdict is a dictionary that provides a default value for missing keys.

Example:

from collections import defaultdict

# Default value is 0
counter = defaultdict(int)
counter["apples"] += 1
print(counter["apples"])  # Outputs: 1
print(counter["oranges"])  # Outputs: 0 (default value)

Key points:

  • Avoids KeyError by providing a default value.
  • Useful for counting or grouping data.
  • Simplifies dictionary operations for freshers.

Que 50. How do you handle command-line arguments in Python using the sys module?

Answer: The sys module’s argv list in Python provides access to command-line arguments passed to a script.

Example:

import sys

print("Script name:", sys.argv[0])
print("Arguments:", sys.argv[1:])

# Run: python script.py arg1 arg2
# Outputs: Script name: script.py
#         Arguments: ['arg1', 'arg2']

Key points:

  • sys.argv[0] is the script name; others are arguments.
  • Useful for scripts accepting user input.
  • Helps freshers create interactive command-line programs.
Python OOPs Interview QuestionsAutomation Testing Interview Questions
Selenium Interview QuestionsFull Stack Developer Interview Questions
Java interview QuestionsTop Coding Interview Questions

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *