Top Python interview questions for a junior developer position

Top Python Interview Questions for Junior Developer Position 1. What is Python? Python is a high-level, interpreted programming language known for its clear syntax and readability. It supports multiple programming paradigms, including procedural, object-oriented, and

Written by: Leo Nguyen

Published on: October 21, 2025

Top Python Interview Questions for Junior Developer Position

1. What is Python?

Python is a high-level, interpreted programming language known for its clear syntax and readability. It supports multiple programming paradigms, including procedural, object-oriented, and functional programming. Python’s extensive libraries and frameworks make it suitable for web development, automation, data analysis, machine learning, and more.

2. Explain the difference between lists and tuples in Python.

Lists and tuples are both built-in data structures in Python used for storing collections of items. The key differences are:

  • Mutability: Lists are mutable, meaning their contents can be changed, while tuples are immutable, so they cannot be modified after creation.
  • Syntax: Lists are defined using square brackets [], e.g., my_list = [1, 2, 3], whereas tuples use parentheses (), e.g., my_tuple = (1, 2, 3).
  • Performance: Tuples can be slightly more efficient in terms of memory and performance when compared to lists.

3. What is PEP 8, and why is it important?

PEP 8 is the Python Enhancement Proposal which defines the style guide for Python code. It promotes a uniform coding style, including naming conventions, code layout, and more. Adhering to PEP 8 enhances code readability and maintainability, facilitating collaboration among developers.

4. Can you explain what a dictionary is in Python?

A dictionary is an unordered collection of key-value pairs in Python. Each key must be unique and immutable, while the value can be of any data type. Dictionaries are defined using curly braces {}. For example, my_dict = {'name': 'John', 'age': 25}. They offer O(1) average time complexity for lookups, making them highly efficient for retrieving data.

5. What are Python decorators?

Decorators are a powerful feature in Python that allows modifying the behavior of functions or methods. A function is passed as an argument to the decorator, which returns a new function. They are commonly used for logging, enforcing access control, instrumentation, or caching results.

def decorator_function(original_function):
    def wrapper_function():
        print("Wrapper executed before {}".format(original_function.__name__))
        return original_function()
    return wrapper_function

@decorator_function
def display():
    print("Display function executed")

display()

6. How do you handle exceptions in Python?

Exceptions in Python can be handled using the try, except, else, and finally blocks. The try block contains the code that may raise an exception. The except block defines responses to specific exceptions. The else block runs if no exceptions occur, and finally, the finally block executes regardless of exceptions.

try:
    value = int(input("Enter a number: "))
except ValueError:
    print("Invalid input, not a number.")
else:
    print("You entered:", value)
finally:
    print("Execution complete.")

7. Describe list comprehensions.

List comprehensions provide a concise way to create lists in Python. They consist of brackets containing an expression followed by a for clause, and optionally, if conditions. This leads to more readable and shorter code.

squared_numbers = [x**2 for x in range(10) if x % 2 == 0]
print(squared_numbers)  # Output: [0, 4, 16, 36, 64]

8. What is the difference between deepcopy and shallow copy?

In Python, copy creates a shallow copy, which means it constructs a new object but populates it with references to the original object’s elements. On the other hand, deepcopy creates a new object and recursively adds copies of nested objects found in the original.

import copy

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

original[0][0] = 'changed'
print(shallow)  # Output: [['changed', 2, 3], [4, 5, 6]]
print(deep)     # Output: [[1, 2, 3], [4, 5, 6]]

9. What are *args and **kwargs in Python?

*args and **kwargs are used to pass a variable number of arguments to a function. *args lets you pass a variable number of non-keyword arguments, while **kwargs allows for passing keyword arguments.

def function_with_args(*args):
    for arg in args:
        print(arg)

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

function_with_args(1, 2, 3)
function_with_kwargs(name="Alice", age=25)

10. How do you read and write files in Python?

Python provides built-in functions for file handling. You can use the open() function to access files, specifying the mode ('r' for reading, 'w' for writing, etc.).

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

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

11. What are Python modules and packages?

A module is a single file containing Python code (functions, classes, or variables) that can be imported into other Python programs. A package is a collection of modules organized in a directory. Packages allow for hierarchical organization of modules and can include an __init__.py file.

12. How can you manage memory in Python?

Python’s memory management is handled by the built-in garbage collector, which automatically deallocates memory for objects that are no longer in use. Developers can manage memory by avoiding circular references and using the del statement to delete variables explicitly when they are no longer needed.

13. What is the difference between is and == in Python?

== compares the values of two objects to check if they are equivalent, while is checks if two references point to the same object in memory.

a = [1, 2, 3]
b = a
c = list(a)

print(a == c)  # True, as they have the same content.
print(a is b)  # True, as both refer to the same object.
print(a is c)  # False, as they are different objects.

14. Explain the concept of virtual environments.

A virtual environment is an isolated environment in which Python libraries can be installed without affecting the global Python installation. It helps manage dependencies and versions for different projects. The venv module is commonly used for creating virtual environments.

# Create a virtual environment
python -m venv myenv

# Activate the virtual environment
# On Windows
myenvScriptsactivate
# On macOS/Linux
source myenv/bin/activate

15. What is self in Python class methods?

In Python classes, self refers to the instance of the class being created. It allows access to attributes and methods associated with that particular object. It must be the first parameter of any method defined in a class.

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

    def bark(self):
        return f"{self.name} barks."

dog = Dog("Fido")
print(dog.bark())  # Output: Fido barks.

16. How can you optimize Python code for performance?

To optimize Python code, consider the following tips:

  • Use built-in functions and libraries, which are often faster than custom implementations.
  • Employ generators for large data sets to save memory.
  • Avoid global variables to reduce the namespace lookup time.
  • Use list comprehensions instead of loops for creating new lists.
  • Profiling your code using tools like cProfile to find bottlenecks.

17. What are lambda functions in Python?

Lambda functions are anonymous functions defined with the lambda keyword. They can have any number of arguments but only one expression. They are useful for small functions that you do not want to formally define using def.

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

18. What is the purpose of the __init__ method?

The __init__ method is a special constructor method in Python that initializes the newly created object. It is called automatically when a new instance of a class is instantiated.

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

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

19. What is the GIL and how does it affect Python programs?

The Global Interpreter Lock (GIL) is a mutex that protects access to Python objects, restricting thread execution to one thread at a time. This can be a limitation for CPU-bound programs in multi-threaded environments, but I/O-bound operations can still benefit from threading.

20. Mention a few popular Python libraries.

Python has a rich ecosystem of libraries that extend its capabilities:

  • NumPy: For numerical computations.
  • Pandas: For data manipulation and analysis.
  • Flask/Django: For web development.
  • Requests: For making HTTP requests.
  • TensorFlow/Keras: For machine learning and deep learning applications.

21. Explain the role of __str__ and __repr__.

__str__ and __repr__ are methods used to define how a class’s objects are represented as strings. __str__ is aimed at creating a user-friendly string representation, while __repr__ is designed for developers’ use, providing a more detailed or unambiguous representation of the object.

class Book:
    def __init__(self, title):
        self.title = title

    def __str__(self):
        return f"Book Title: {self.title}"

    def __repr__(self):
        return f"Book({self.title!r})"

book = Book("1984")
print(str(book))   # Output: Book Title: 1984
print(repr(book))  # Output: Book('1984')

22. What does the with statement do?

The with statement in Python simplifies exception handling by encapsulating common preparation and cleanup tasks. It is commonly used for file operations to ensure the file is properly closed after its suite finishes, even if an error occurs.

with open("file.txt", "w") as file:
    file.write("Hello, World!")
# File is automatically closed after this block.

23. What are assertions in Python?

Assertions are a way to set conditions in your code that you expect to be true. If the condition evaluates to false, an AssertionError is raised. They are useful for debugging, allowing you to catch errors during development.

def square(x):
    assert x >= 0, "Negative value error"
    return x * x

24. How does Python support memory management?

Python uses a combination of reference counting and garbage collection to manage memory. The automatic garbage collector frees up memory occupied by objects no longer in use. This helps prevent memory leaks.

25. What is the difference between a thread and a process in Python?

A thread is a lightweight subprocess, the smallest unit of processing, which shares memory space with other threads in the same process. A process, however, is a heavier entity with its own memory space. Python’s GIL means threads can run in a single process, potentially leading to performance limitations in CPU-bound tasks.

26. Explain the term “memoization” in Python.

Memoization is an optimization technique that involves storing the results of expensive function calls and reusing them when the same inputs occur again. This is commonly implemented using decorators in Python.

from functools import lru_cache

@lru_cache(maxsize=None)
def fib(n):
    if n < 2:
        return n
    return fib(n-1) + fib(n-2)

print(fib(10))  # Output: 55

27. What is the purpose of the pass statement?

The pass statement is a null operation that acts as a placeholder in blocks of code where syntactically some code is required, but no action needs to be performed. It can be useful in defining functions or loops that you want to implement later.

def function_to_implement_later():
    pass

28. How can you create a custom exception in Python?

You can create a custom exception by defining a new class that derives from the built-in Exception class. This allows you to define specific exception types and manage them effectively in your application.

class MyCustomError(Exception):
    pass

def raise_custom_error():
    raise MyCustomError("This is my custom error.")

try:
    raise_custom_error()
except MyCustomError as e:
    print(e)

29. What do the in keyword and not in do in Python?

The in keyword checks if a value exists in a collection (such as a list, tuple, or string), returning True if found, and False otherwise. Conversely, not in does the opposite, checking if a value does not exist in the collection.

my_list = [1, 2, 3]
print(2 in my_list)      # Output: True
print(4 not in my_list)  # Output: True

30. How would you reverse a list in Python?

You can reverse a list in Python using either the reverse() method or slicing. The reverse() method reverses the list in place, while slicing creates a new reversed list.

my_list = [1, 2, 3, 4]
my_list.reverse()  # In-place reversal
print(my_list)     # Output: [4, 3, 2, 1]

reversed_list = my_list[::-1]  # Slicing
print(reversed_list)             # Output: [1, 2, 3, 4]

31. How can you sort a list in Python?

Lists in Python can be sorted using the sort() method, which sorts the list in place, or the sorted() function, which returns a new sorted list.

numbers = [3, 1, 4, 2]
numbers.sort()
print(numbers)  # Output: [1, 2, 3, 4]

new_sorted_numbers = sorted(numbers, reverse=True)
print(new_sorted_numbers)  # Output: [4, 3, 2, 1]

32. Explain how Python’s map() function works.

The map() function applies a given function to all items in an iterable, returning an iterator of the results. It is often used for applying a transformation over an iterable efficiently.

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

33. Describe what filter() does in Python.

The filter() function is used to construct an iterator from elements of an iterable for which a function returns True. This is particularly useful for filtering collections according to specific criteria.

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

34. What is the difference between a synchronous and asynchronous function in Python?

Synchronous functions run sequentially, blocking the execution flow until the current function is complete. Asynchronous functions, on the other hand, can execute without waiting for other functions to complete, enabling better performance for I/O-bound tasks.

35. What is the purpose of the async and await keywords?

The async keyword is used to define an asynchronous function, while await is used to pause the execution of an async function and wait for the result of a given awaitable, like another async function. This allows for more responsive applications that can handle multiple tasks simultaneously.

import asyncio

async def say_hello():
    await asyncio.sleep(1)
    print("Hello!")

asyncio.run(say_hello())

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

Key differences between Python 2 and Python 3 include:

  • Print Statement: In Python 2, print is a statement, while in Python 3, it is a function.
  • Integer Division: In Python 2, division of integers returns an integer while Python 3 returns a float.
  • Unicode: Strings in Python 3 are Unicode by default, while Python 2 uses ASCII.
  • Libraries and Support: Python 3 has better support for modern libraries and is actively maintained, while Python 2 reached its end-of-life in January 2020.

37. What is a context manager in Python?

A context manager is a Python construct that allows you to allocate and release resources precisely when you want. The most common way to create a context manager is using the with statement, which ensures that resources are cleaned up after use.

class MyContext:
    def __enter__(self):
        print("Entering the context.")
        return self

    def __exit__(self, exc_type, exc_value, traceback):
        print("Exiting the context.")

with MyContext():
    print("Inside the context.")

38. Explain the concept of inheritance in Python.

Inheritance allows a class (child class) to inherit attributes and methods from another class (parent class). This facilitates code reusability and hierarchical class organization.

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

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

dog = Dog()
print(dog.speak())  # Output: Animal speaks
print(dog.bark())   # Output: Dog barks

39. How do you create a class property in Python?

Class properties can be created using the property() built-in function or the @property decorator. This allows you to define methods that can be accessed like attributes.

class Circle:
    def __init__(self, radius):
        self._radius = radius

    @property
    def area(self):
        return 3.14 * (self._radius ** 2)

circle = Circle(5)
print(circle.area)  # Output: 78.5

40. What are unit tests in Python?

Unit tests are small, automated tests designed to verify that individual units of code (usually functions or methods) work as intended. Using the unittest framework, you can create tests to ensure that your code behaves correctly.

import unittest

def add(x, y):
    return x + y

class TestAddFunction(unittest.TestCase):
    def test_add(self):
        self.assertEqual(add(1, 2), 3)

if __name__ == '__main__':
    unittest.main()

41. Describe how to access environment variables in Python.

You can access environment variables using the os module. The os.environ dictionary-like object provides a way to retrieve environment variables.

import os

database_url = os.environ.get('DATABASE_URL', 'default_value')
print(database_url)

42. Explain the __main__ block in Python.

The if __name__ == "__main__": block allows Python code to determine if a script is being run directly or imported as a module in another script. Code under this block will only execute when the script is run directly.

def main():
    print("This is the main function.")

if __name__ == "__main__":
    main()

43. What are f-strings in Python?

Formatted string literals, known as f-strings, provide a way to embed expressions inside string literals, using curly braces {}. This feature was introduced in Python 3.6, enhancing string formatting capabilities.

name = "Alice"
greeting = f"Hello, {name}!"
print(greeting)  # Output: Hello, Alice!

44. How can you check if a variable is of a specific type?

You can check a variable’s type using the built-in isinstance() function, which returns True if the variable is an instance of a specified class or tuple of classes.

num = 5
print(isinstance(num, int))  # Output: True

45. What is type hinting?

Type hinting is a feature that allows you to annotate functions with type information, which helps with code readability and static analysis. It is not enforced at runtime but is useful for documentation and type checkers.

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

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

46. How do you create a generator in Python?

A generator is a special type of iterator defined using a function with yield statements. It allows you to iterate over values without storing them all simultaneously, which is memory efficient.

def countdown(n):
    while n > 0:
        yield n
        n -= 1

for num in countdown(5):
    print(num)

47. What is the purpose of the zip() function?

The zip() function takes multiple iterables and returns an iterator of tuples, where each tuple contains elements from the corresponding position in the input iterables.

names = ["Alice", "Bob", "Charlie"]
scores = [85, 90, 95]
combined = zip(names, scores)
print(list(combined))  # Output: [('Alice', 85), ('Bob', 90), ('Charlie', 95)]

48. How do you implement a singleton pattern in Python?

The singleton pattern ensures that a class has only one instance and provides a global access point to it. This can be achieved by overriding the __new__ method in a class.

class Singleton:
    _instance = None

    def __new__(cls):
        if cls._instance is None:
            cls._instance = super(Singleton, cls).__new__(cls)
        return cls._instance

singleton1 = Singleton()
singleton2 = Singleton()
print(singleton1 is singleton2)  # Output: True

49. What is multithreading in Python?

Multithreading is the concurrent execution of multiple threads within a single process. Threads share the same memory space, making it efficient for I/O-bound tasks. However, due to the GIL, Python threads may not provide the same performance boost for CPU-bound tasks.

50. What are Python’s built-in data types?

Python includes several built-in data types, including:

  • Numeric Types: int, float, complex
  • Sequence Types: list, tuple, range
  • Text Type: str
  • Mapping Type: dict
  • Set Types: set, frozenset
  • Boolean Type: bool
  • Binary Types: bytes, bytearray, memoryview

51. Describe the sorted() function.

The sorted() function returns a new list containing all items from the iterable in ascending order. It accepts optional parameters for key functions and reverse sorting.

unsorted_list = [4, 2, 1, 3]
sorted_list = sorted(unsorted_list)
print(sorted_list)  # Output: [1, 2, 3, 4]

52. How do you use the itertools library?

The itertools module provides functions that create iterators for efficient looping. Common functions include count(), cycle(), and combinations(), which enable advanced iteration patterns.

import itertools

for item in itertools.count(start=5, step=2):
    if item > 20:
        break
    print(item)  # Output: 5, 7, 9, 11, 13, 15, 17, 19

53. What is the use of re module in Python?

The re module offers functions for working with regular expressions, enabling complex pattern matching and manipulation of strings. This is helpful for searching, matching, and replacing parts of strings.

import re

pattern = r"d+"
text = "There are 2 apples and 6 oranges."
matches = re.findall(pattern, text)
print(matches)  # Output: ['2', '6']

54. What does __repr__ do, and why is it important?

The __repr__ method is designed to produce a string representation of an object that is unambiguous, aimed at developers. It can be helpful for debugging and should ideally return a string that can be evaluated by Python’s interpreter.

55. How do you check for duplicates in a list?

You can check for duplicates in a list by converting the list to a set, which removes duplicates, and then comparing its length with the original list.

my_list = [1, 2, 3, 2]
has_duplicates = len(my_list) != len(set(my_list))
print(has_duplicates)  # Output: True

56. What are slices in Python?

Slices allow you to access a portion of a sequence type (like lists, tuples, or strings) by specifying a start, stop, and step value.

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

57. How can you convert a list to a string in Python?

You can convert a list to a string using the join() method, which joins elements using a specified separator.

words = ["Hello", "World"]
sentence = " ".join(words)
print(sentence)  # Output: Hello World

58. Describe duck typing in Python.

Duck typing is a programming concept where an object’s suitability is determined by the presence of certain methods and properties, rather than the actual type of the object. In Python, if an object behaves like a certain type, it can be used wherever that type is expected.

class Duck:
    def quack(self):
        return "Quack!"

class Person:
    def quack(self):
        return "I'm quacking!"

def make_it_quack(thing):
    print(thing.quack())

make_it_quack(Duck())   # Works
make_it_quack(Person()) # Works too

59. What is the purpose of the assert statement?

The assert statement is used for debugging purposes. It tests a condition and triggers an AssertionError if the condition evaluates to False. This is useful for catching bugs during development.

x = 10
assert x > 0, "x should be positive" # This passes
assert x < 0, "x should be negative" # This raises an AssertionError

60. What is the method resolution order (MRO)?

MRO in Python determines the order in which classes are searched when executing a method. It is especially relevant in multiple inheritance scenarios. The MRO can be viewed using the __mro__ attribute or the mro() method.

class A: pass
class B(A): pass
class C(A): pass
class D(B, C): pass

print(D.mro())  # Output: [<class '__main__.D'>, <class '__main__.B'>, <class '__main__.C'>, <class '__main__.A'>, <class 'object'>]

61. How do you compare two dictionaries?

You can compare two dictionaries directly using the equality operator ==, which checks if both dictionaries have the same key-value pairs.

dict1 = {'key1': 'value1', 'key2': 'value2'}
dict2 = {'key1': 'value1', 'key2': 'value2'}
print(dict1 == dict2)  # Output: True

62. How do you handle JSON data in Python?

You can handle JSON data using the json module. You can serialize Python objects to JSON using json.dump() or json.dumps(), and deserialize JSON back to Python objects using json.load() or json.loads().

import json

data = {'name': 'Alice', 'age': 30}
json_data = json.dumps(data)  # Serialize to JSON
print(json_data)

loaded_data = json.loads(json_data)  # Deserialize back to Python object
print(loaded_data)  # Output: {'name': 'Alice', 'age': 30}

63. What is the difference between find() and index() for strings?

Both find() and index() are used to locate a substring in a string. The main difference is that find() returns -1 if the substring is not found, while index() raises a ValueError.

text = "Hello, World!"
print(text.find("World"))  # Output: 7
print(text.index("Python")) # Raises ValueError

64. How can you implement a stack using a Python list?

A stack can be implemented using a Python list, utilizing append() for pushing and pop() for popping elements off the stack.

stack = []
stack.append(1)
stack.append(2)
stack.append(3)

print(stack.pop())  # Output: 3
print(stack)        # Output: [1, 2]

65. What is a Queue in Python?

A queue is a data structure that follows the First-In-First-Out (FIFO) principle. You can implement a queue using collections.deque for efficient appends and pops from either end.

from collections import deque

queue = deque()
queue.append(1)
queue.append(2)
queue.append(3)

print(queue.popleft())  # Output: 1
print(queue)            # Output: deque([2, 3])

66. What are the advantages of using Python for web development?

Python offers several advantages for web development:

  • Frameworks: Popular frameworks like Django and Flask simplify web development.
  • Readability: Python’s clean syntax promotes readability and maintainability.
  • Community support: A large community provides extensive libraries and resources.
  • Rapid development: Python’s simplicity enables faster development cycles.

67. How can you create a rest API in Python?

You can create a REST API in Python using frameworks like Flask or Django REST Framework. Flask is more lightweight, while Django REST is better for complex applications.

from flask import Flask, jsonify

app = Flask(__name__)

@app.route('/api', methods=['GET'])
def get_data():
    return jsonify({'message': 'Hello, World!'})

if __name__ == "__main__":
    app.run()

68. What are the main differences between Python and Java?

Python is dynamically typed and interpreted, resulting in faster development. Java is statically typed and compiled, making it more performance-oriented. Python’s syntax is more concise, while Java’s syntax is more verbose.

69. How do you handle multi-threading in Python?

You can manage multi-threading in Python by utilizing the threading module, which provides a high-level interface for working with threads. You can create and start threads, and handle synchronization issues using locks.

import threading

def thread_function(name):
    print(f"Thread {name} starting")

thread = threading.Thread(target=thread_function, args=(1,))
thread.start()
thread.join()

70. What is a lambda expression?

A lambda expression is a small anonymous function defined using the lambda keyword. It can take any number of arguments but can only have one expression, often used where functions are required temporarily.

multiply = lambda x, y: x * y
print(multiply(2, 3))  # Output: 6

71. Explain the difference between join() and leave().

In Python, join() is used to concatenate strings or join threads. However, leave() is not a standard method in Python. Instead, you may refer to the exit() method or terminate() method for quitting threads or processes.

72. Describe the type and isinstance.

The type() function returns the type of an object, while isinstance() checks whether an object is an instance or a subclass of a given class or tuple of classes.

num = 123
print(type(num))          # Output: <class 'int'>
print(isinstance(num, int))  # Output: True

73. What are the main advantages of using a version control system?

Version control systems like Git offer several advantages:

  • Collaboration: Multiple developers can work on a project simultaneously without conflicts.
  • History: Track changes and view previous versions of code.
  • Branching: Experiment with new features without affecting the main codebase.

74. How do you perform unit testing in Python?

You can perform unit testing using the unittest testing framework. This involves creating test cases, executing them, and asserting expected outcomes.

import unittest

def add(x, y):
    return x + y

class TestMath(unittest.TestCase):
    def test_add(self):
        self.assertEqual(add(1, 2), 3)

if __name__ == '__main__':
    unittest.main()

75. Explain the concept of try-except-else-finally.

In Python, try blocks contain the code that might raise an exception. except captures and handles exceptions, else runs code if the try succeeds, and finally executes code regardless of whether an exception occurred.

try:
    print(1 / 0)
except ZeroDivisionError:
    print("Cannot divide by zero.")
else:
    print("Division performed successfully.")
finally:
    print("Execution finished.")

76. How can you remove duplicates from a list?

You can remove duplicates from a list by converting it to a set and back to a list:

my_list = [1, 2, 2, 3, 4]
unique_list = list(set(my_list))
print(unique_list)  # Output: [1, 2, 3, 4]

77. What is the purpose of the @classmethod decorator?

The @classmethod decorator allows you to define a method that operates on the class itself rather than an instance of the class. This method receives the class as its first argument, conventionally named cls.

class MyClass:
    value = 0

    @classmethod
    def set_value(cls, new_value):
        cls.value = new_value

MyClass.set_value(5)
print(MyClass.value)  # Output: 5

78. What is the difference between callable and iterable in Python?

A callable is an object that can be called as a function, like functions and classes. An iterable is an object capable of returning its members one at a time, such as lists and strings. All callables are not iterables, and not all iterables are callables.

79. How can you read CSV files in Python?

You can read CSV files in Python using the csv module, which provides functionality to both read from and write to CSV files.

import csv

with open('data.csv', mode='r') as file:
    reader = csv.reader(file)
    for row in reader:
        print(row)

80. What is the difference between a function and a method?

A function is a standalone block of code that performs a task and is defined using the def keyword. A method, on the other hand, is a function that is associated with an object and is defined within a class.

81. What is the purpose of the enumerate() function?

The enumerate() function adds a counter to an iterable and returns it as an enumerating object. This is useful when you need both the index and the value from a sequence.

my_list = ['a', 'b', 'c']
for index, value in enumerate(my_list):
    print(index, value)

82. What are sets in Python?

Sets are an unordered collection of unique elements. They are mutable, do not allow duplicates, and provide efficient operations for membership tests and set operations.

my_set = {1, 2, 3}
my_set.add(2)  # No effect, as 2 is already in the set
print(my_set)  # Output: {1, 2, 3}

83. How can you implement an algorithm to find the maximum of three numbers?

You can find the maximum of three numbers using the built-in max() function or conditional statements.

def max_of_three(a, b, c):
    return max(a, b, c)

print(max_of_three(5, 10, 3))  # Output: 10

84. What is recursion in Python?

Recursion is a technique where a function calls itself to solve a problem. It typically involves a base case to terminate the recursion and ensure it does not run indefinitely.

def factorial(n):
    if n == 0:
        return 1
    return n * factorial(n - 1)

print(factorial(5))  # Output: 120

85. Describe the difference between input and output redirection in Python.

Input redirection allows a program to take input from a source other than the keyboard (like a file). Output redirection sends program output to a destination other than the display (like a file). This feature is achieved through command-line capabilities or by manipulating sys.stdin and sys.stdout in code.

86. How would you implement a queue using a Python list?

You can implement a queue using a list, with append() to enqueue and pop(0) to dequeue elements.

queue = []
queue.append(1)  # Enqueue
queue.append(2)
print(queue.pop(0))  # Dequeue, Output: 1

87. How can you make a Python script executable?

To make a Python script executable, you can add a shebang line (e.g., #!/usr/bin/env python3) at the start of the script and set execute permissions using chmod +x script.py.

88. Describe how to implement error handling in Python.

Error handling in Python is managed through the try-except block. You can catch specific exceptions or general exceptions, enabling graceful handling of errors rather than allowing the program to crash.

try:
    1 / 0
except ZeroDivisionError:
    print("Division by zero is not allowed.")

89. Explain how to update a dictionary.

You can update a dictionary by using the assignment operator, or the update() method. Both allow adding or modifying key-value pairs.

my_dict = {'a': 1, 'b': 2}
my_dict['b'] = 5  # Modify existing key
my_dict['c'] = 3  # Add new key
print(my_dict)  # Output: {'a': 1, 'b': 5, 'c': 3}

90. How do you create an empty tuple in Python?

You can create an empty tuple by using parentheses with no elements inside them.

empty_tuple = ()
print(empty_tuple)  # Output: ()

91. Explain the use of the __init__.py file.

The __init__.py file indicates that the directory it resides in should be treated as a Python package. It can be empty or contain code to initialize the package, enabling the inclusion of module-level variables or setup code.

92. How can you get the current working directory in Python?

You can get the current working directory using the os.getcwd() function from the os module.

import os

current_directory = os.getcwd()
print(current_directory)

93. Describe how to convert a Python list to a set.

You can convert a list to a set using the set() constructor, which removes duplicate items from the list.

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

94. What is the difference between while True and for loop in Python?

A while True loop runs indefinitely until manually interrupted or a break condition is met, whereas a for loop iterates over a finite sequence or range of values.

95. How would you implement a timer in Python?

You can implement a timer in Python using the time module’s time() or sleep() functions.

import time

start_time = time.time()
time.sleep(2)  # Wait for 2 seconds
end_time = time.time()
elapsed_time = end_time - start_time
print(f"Elapsed time: {elapsed_time} seconds")

96. Explain what kwargs is used for.

The **kwargs syntax in function definitions stands for “keyword arguments,” allowing you to pass a variable number of keyword arguments to the function. This enables flexible parameter handling.

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

print_kwargs(name="Alice", age=25)

97. What is the purpose of the sorted() function’s key argument?

The key argument allows you to specify a function to be called on each element before making comparisons during sorting. This is useful for sorting complex objects or custom criteria.

data = ['Alice', 'Bob', 'Charlie']
sorted_data = sorted(data, key=lambda x: len(x))
print(sorted_data)  # Output: ['Bob', 'Alice', 'Charlie']

98. Discuss the importance of code comments.

Code comments are essential for improving the readability and maintainability of code. They explain the purpose of code segments, making it easier for yourself and others to understand your logic and decisions later.

99. What is the random module used for?

The random module in Python provides functions for generating random numbers, selecting random elements from a sequence, and various probabilistic operations. It is frequently used in games, simulations, and testing.

import random

print(random.randint(1, 10))  # Output: a random integer between 1 and 10

100. How can you concatenate two dictionaries in Python?

You can concatenate two dictionaries using the update() method, or in Python 3.9 and above, by using the merge operator |.

dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}

dict1.update(dict2)  # Updates dict1 with key-value pairs from dict2
print(dict1)  # Output: {'a': 1, 'b': 3, 'c': 4}

merged_dict = dict1 | dict2  # Merge two dictionaries
print(merged_dict)  # Output: {'a': 1, 'b': 3, 'c': 4}

Leave a Comment

Previous

FastAPI vs. Django: Choosing the Right Framework for Your REST API

Next

Simple instructions for using Windows Subsystem for Linux (WSL) for Python development