Show List

Python Interview Questions

  • What is Python and what is it used for?

Python is a high-level, interpreted programming language that is used for a wide range of applications, including web development, scientific computing, data analysis, and artificial intelligence. It is known for its readability and ease of use, making it a popular choice for beginners and experienced programmers alike.

  • What is the difference between a tuple and a list in Python?

A tuple is an immutable, ordered collection of elements, while a list is a mutable, ordered collection of elements. Tuples are typically used to store collections of related data that should not be changed, while lists are used to store collections of data that need to be modified.

  • What is the purpose of the "init" method in Python?

The __init__ method is the constructor method in Python. It is called when an object is created from a class and is used to initialize the attributes of the object. The __init__ method is automatically called when a new object is created and it is used to set the default values for the object's attributes.

  • What is the difference between local and global variables in Python?

A local variable is a variable that is defined within a function and is only accessible within that function. A global variable is a variable that is defined outside of a function and is accessible from anywhere in the code. Global variables can be accessed from within functions, but local variables cannot be accessed from outside of their function.

  • How do you create a function in Python?

In Python, you can create a function using the def keyword, followed by the function name, a set of parentheses, and a colon. The code inside the function is indented and is executed when the function is called. For example:

scss
Copy code
def greet(): print("Hello, world!")
  • What is a dictionary in Python and how do you create one?

A dictionary in Python is a collection of key-value pairs, where each key is associated with a value. You can create a dictionary using curly braces {} and separating the key-value pairs with colons. For example:

makefile
Copy code
person = {"name": "John Doe", "age": 30}
  • What is the difference between the "append" and "extend" methods in a list?

The append method is used to add a single element to the end of a list, while the extend method is used to add multiple elements to a list. The extend method takes another list as an argument and adds each element from that list to the end of the original list.

  • What is an exception in Python and how do you handle them?

An exception in Python is an error that occurs during the execution of a program. You can handle exceptions in Python using a try-except block. The code that might raise an exception is placed in the try block, and the code that handles the exception is placed in the except block. For example:

python
Copy code
try: # code that might raise an exception x = 1 / 0 except ZeroDivisionError: # code to handle the exception print("Cannot divide by zero.")
  • What is the difference between shallow and deep copying in Python?

Shallow copying is a copy of the reference to an object, rather than a copy of the object itself. This means that if the original object is modified, the copy will also be modified. Deep copying is a copy of the object itself and all of its nested objects. This means that if the original object is modified, the copy will not be affected.

  • What is the difference between a stack and a queue in Python?

A stack is a data structure that follows the Last In First Out (LIFO) principle, meaning that the last element added to the stack is the first one to be removed. A queue is a data structure that follows the First In First Out (FIFO) principle, meaning that the first element added to the queue is the first one to be removed.

  • What is the difference between a list and an array in Python?

A list in Python is a dynamic, ordered collection of elements, while an array in Python is a static, ordered collection of elements that have a fixed size. Lists can be resized dynamically, but arrays cannot. Lists can store elements of different data types, while arrays can only store elements of the same data type.

  • What is the "map" function in Python and how is it used?

The map function in Python is used to apply a function to every item in an iterable (e.g., a list) and return a new iterable with the results. For example:

python
Copy code
def square(x): return x * x numbers = [1, 2, 3, 4, 5] squared_numbers = list(map(square, numbers)) print(squared_numbers) # Output: [1, 4, 9, 16, 25]
  • What is the "lambda" function in Python and how is it used?

A lambda function in Python is a small, anonymous function that is defined using the lambda keyword. lambda functions are used to create short, throwaway functions that can be passed as arguments to other functions. For example:

python
Copy code
squared = lambda x: x * x print(squared(5)) # Output: 25
  • What is the difference between a tuple and a set in Python?

A tuple in Python is an immutable, ordered collection of elements, while a set is an unordered collection of unique elements. Tuples maintain the order of the elements, but sets do not. Sets also do not allow duplicate elements, while tuples can contain duplicate elements.

  • What is the "assert" statement in Python and how is it used?

The assert statement in Python is used to check if a condition is true, and raise an exception if it is not. The assert statement is used for debugging purposes, and is typically removed from the code before it is released. For example:

python
Copy code
assert 5 + 5 == 10 # No exception is raised, because the condition is true assert 5 + 5 == 11 # AssertionError is raised, because the condition is false
  • What is the "with" statement in Python and how is it used?

The with statement in Python is used to wrap the execution of a block of code with methods defined by a context manager. The with statement automatically takes care of cleaning up resources, such as file handles, that are used in the block of code. For example:

python
Copy code
with open("file.txt", "r") as file: contents = file.read() print(contents) # The file is automatically closed after the block of code is executed
  • What is the difference between a module and a package in Python?

A module in Python is a single file that contains Python code, while a package is a collection of modules organized into a directory structure. Packages can contain multiple modules and other packages, and allow for a more organized and reusable code structure.

  • What is the "try-except" block in Python and how is it used?

The try-except block in Python is used to handle exceptions, or errors, that occur during the execution of a block of code. The try block contains the code that may raise an exception, and the except block contains the code that will be executed if an exception is raised. For example:

python
Copy code
try: 5/0 except ZeroDivisionError: print("Cannot divide by zero") # Output: Cannot divide by zero
  • What is the "super" function in Python and how is it used?

The super function in Python is used to call a method in a parent class from a subclass. The super function allows you to access methods in the parent class that have been overridden in the subclass. For example:

ruby
Copy code
class Shape: def area(self): pass class Square(Shape): def __init__(self, side): self.side = side def area(self): return self.side ** 2 class Cube(Square): def volume(self): return super().area() * self.side cube = Cube(5) print(cube.volume()) # Output: 125
  • What is the difference between a static method and a class method in Python?

A static method in Python is a method that belongs to a class and is not bound to an instance of the class. A static method does not have access to the class or instance, and is defined using the @staticmethod decorator. A class method in Python is a method that belongs to a class and is bound to the class, rather than the instance of the class. A class method is defined using the @classmethod decorator.

  • What is a decorator in Python and how is it used?

A decorator in Python is a special type of function that is used to modify the behavior of another function or class. Decorators are defined using the @ symbol followed by the name of the decorator function, and can be used to add additional functionality to a function or class without modifying its code. For example:

python
Copy code
def logging_decorator(func): def wrapper(*args, **kwargs): print("Function called:", func.__name__) result = func(*args, **kwargs) print("Result:", result) return result return wrapper @logging_decorator def add(a, b): return a + b print(add(1, 2)) # Output: # Function called: add # Result: 3 # 3
  • What is the difference between a deep copy and a shallow copy in Python?

A deep copy in Python is a copy of an object that includes all of the objects within the original object, while a shallow copy only includes the objects that are referenced by the original object. In a shallow copy, the objects within the copied object are not copied, but instead, references to the original objects are created.

  • What is the "assert" statement in Python and how is it used?

The assert statement in Python is used to test a condition, and raise an AssertionError if the condition is not true. The assert statement is used for debugging purposes and is typically removed from code in production. For example:

python
Copy code
assert 5 > 2, "Five is not greater than two" # No output, assertion is true assert 5 < 2, "Five is not less than two" # Output: AssertionError: Five is not less than two
  • What is a generator expression in Python and how is it used?

A generator expression in Python is a compact way to generate a generator object, similar to a list comprehension, but instead of returning a list, it returns a generator. Generator expressions use parentheses instead of square brackets, and are defined using a similar syntax to list comprehensions. For example:

python
Copy code
numbers = (i * 2 for i in range(10)) print(next(numbers)) # Output: 0 print(next(numbers)) # Output: 2
  • What is the difference between the "is" and "==" operators in Python?

The is operator in Python compares the identity of two objects, while the == operator compares the values of two objects. The is operator returns True if two variables refer to the same object in memory, while the == operator returns True if the values of two variables are equal. For example:

css
Copy code
a = [1, 2, 3] b = [1, 2, 3] c = a print(a is b) # Output: False print(a is c) # Output: True print(a == b) # Output: True
  • How would you handle missing data in a Pandas DataFrame?

There are several ways to handle missing data in a Pandas DataFrame, including:

  • Dropping missing values using the dropna() method.
  • Replacing missing values with a specified value using the fillna() method.
  • Interpolating missing values using the interpolate() method.
  • Forward-filling or backward-filling missing values using the fillna() method with the method parameter set to 'ffill' or 'bfill'.
  • What is the purpose of the "else" statement in a for loop or while loop in Python?

The else statement in a for loop or while loop in Python is executed after the loop has finished iterating, but only if the loop completed normally (i.e., was not terminated by a break statement). The else block is useful for performing additional processing after the loop has completed.

  • What is the difference between a list and a tuple in Python?

A list in Python is a mutable, ordered collection of items, while a tuple is an immutable, ordered collection of items. Lists are defined using square brackets [], while tuples are defined using parentheses (). Lists can be modified after they are created, while tuples cannot be modified once they are created.

  • How would you sort a list of dictionaries in Python by a specific value in the dictionary?

You can sort a list of dictionaries in Python by a specific value in the dictionary using the sorted() function and passing the key parameter a function that returns the value by which you want to sort. For example:

css
Copy code
data = [{'name': 'John', 'age': 25}, {'name': 'Jane', 'age': 30}, {'name': 'Jim', 'age': 20}] sorted_data = sorted(data, key=lambda x: x['age']) print(sorted_data) # Output: # [{'name': 'Jim', 'age': 20}, {'name': 'John', 'age': 25}, {'name': 'Jane', 'age': 30}]
  • How would you reverse a string in Python?

You can reverse a string in Python by slicing the string with negative step size. For example:

scss
Copy code
text = "Hello, World!" reversed_text = text[::-1] print(reversed_text) # Output: "!dlroW ,olleH"
  • What is a dictionary in Python and how is it used?

A dictionary in Python is an unordered collection of key-value pairs, where each key is unique. Dictionaries are defined using curly braces {} and are used to store and retrieve values based on their associated keys. For example:

python
Copy code
data = {'name': 'John', 'age': 25, 'city': 'London'} print(data['name']) # Output: John
  • What is the difference between a shallow copy and a deep copy in Python?

A shallow copy in Python is a copy of an object that refers to the same underlying objects as the original object, while a deep copy is a copy of an object that has its own independent copy of all objects referenced by the original object. In a shallow copy, changes made to the copied object will be reflected in the original object, while changes made to a deep copy will not be reflected in the original object.

  • What is the difference between a Python generator and a list?

A Python generator is a special type of iterator that generates values one-by-one as they are needed, rather than creating a large list in memory. Generators are defined using the yield keyword, and can be created using a generator expression or a generator function. Generators are often more memory-efficient than lists and can be used to iterate over large amounts of data without running out of memory.

  • What is the purpose of the with statement in Python?

The with statement in Python is used to wrap the execution of a block of code with methods defined by a context manager. The purpose of the with statement is to ensure that resources are properly managed, even if an exception occurs within the block of code. The with statement automatically handles the management of resources, such as file handles, network connections, and lock acquisitions, without requiring explicit calls to close() or release().

  • What is the difference between a Python tuple and a list?

A tuple in Python is an immutable, ordered collection of items, while a list is a mutable, ordered collection of items. Tuples are defined using parentheses (), while lists are defined using square brackets []. Tuples cannot be modified after they are created, while lists can be modified.

  • What is the purpose of the __init__ method in a Python class?

The __init__ method in a Python class is a special method that is called when an object is created from the class. The __init__ method is used to initialize the attributes of the object, and can accept arguments to set the initial values of those attributes. The __init__ method is often referred to as the class constructor.

  • How would you compare two dictionaries in Python?

You can compare two dictionaries in Python using the == operator, which returns True if the dictionaries are equal and False if they are not. Equality between dictionaries is determined by the equality of their keys and values. For example:

python
Copy code
dict1 = {'name': 'John', 'age': 25} dict2 = {'name': 'John', 'age': 25} print(dict1 == dict2) # Output: True
  • What is the difference between the sort and sorted methods for lists in Python?

The sort method for lists in Python sorts the list in-place, modifying the original list, while the sorted function returns a new sorted list without modifying the original list. For example:

scss
Copy code
data = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5] data.sort() print(data) # Output: [1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9] sorted_data = sorted(data) print(sorted_data) # Output: [1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]
  • How would you remove duplicates from a list in Python?

You can remove duplicates from a list in Python using a set, as sets do not allow duplicates. You can convert the list to a set, then convert it back to a list, like this:

scss
Copy code
data = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5] unique_data = list(set(data)) print(unique_data) # Output: [1, 2, 3, 4, 5, 6, 9]
  • What is a decorator in Python, and how would you use one?

A decorator in Python is a special type of function that can be used to modify the behavior of another function. Decorators are often used to add additional functionality to a function, such as logging, timing, or authorization checks. Decorators are applied to functions using the @ symbol, followed by the name of the decorator function. For example:

python
Copy code
def log_decorator(func): def wrapper(*args, **kwargs): print(f"Calling function {func.__name__} with arguments {args} and keyword arguments {kwargs}") result = func(*args, **kwargs) print(f"Function {func.__name__} returned {result}") return result return wrapper @log_decorator def add(a, b): return a + b print(add(3, 4)) # Output: # Calling function add with arguments (3, 4) and keyword arguments {} # Function add returned 7 # 7
  • What is the purpose of the else clause in a for loop or while loop in Python?

The else clause in a for loop or while loop in Python is executed only when the loop terminates normally, i.e., when the loop condition is False. It is not executed if the loop is terminated by a break statement. For example:

python
Copy code
data = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5] for i in data: if i == 4: break else: print("The number 4 was not found in the list") # Output: data = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5, 4] for i in data: if i == 4: break else: print("The number 4 was not found in the list") # Output: The number 4 was not found in the list
  • What is the difference between a list and a tuple in Python?

The main difference between a list and a tuple in Python is that a list is mutable, while a tuple is immutable. This means that you can modify a list after it has been created, but you cannot modify a tuple. For example:

kotlin
Copy code
data = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5] data[0] = 10 print(data) # Output: [10, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5] data = (3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5) data[0] = 10 # Output: TypeError: 'tuple' object does not support item assignment
  • What is the purpose of the __init__ method in a Python class?

The __init__ method in a Python class is the constructor of the class. It is called when a new instance of the class is created, and is used to initialize the attributes of the class. For example:

python
Copy code
class Person: def __init__(self, name, age): self.name = name self.age = age person = Person("John Doe", 30) print(person.name) # Output: John Doe print(person.age) # Output: 30
  • What is a decorator in Python and how do you use it?

A decorator in Python is a special type of function that can be used to modify the behavior of another function. Decorators are applied to functions using the @ symbol, followed by the name of the decorator function. For example:

python
Copy code
def my_decorator(func): def wrapper(*args, **kwargs): print("Something is happening before the function is called.") result = func(*args, **kwargs) print("Something is happening after the function is called.") return result return wrapper @my_decorator def say_hello(name): print(f"Hello, {name}!") say_hello("John Doe") # Output: # Something is happening before the function is called. # Hello, John Doe! # Something is happening after the function is called.
  • What is the difference between a list comprehension and a generator expression in Python?

The main difference between a list comprehension and a generator expression in Python is that a list comprehension creates a list in memory, while a generator expression generates the values one at a time on the fly. This can be more memory efficient for large data sets. For example:

python
Copy code
# List comprehension data = [x**2 for x in range(10)] print(data) # Output: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] # Generator expression data = (x**2 for x in range(10)) print(data) # Output: <generator object <genexpr> at 0x7f9e91c06d58>
  • How do you handle exceptions in Python?

You handle exceptions in Python using the try and except keywords. The code that could raise an exception is placed in a try block, and the code that should be executed in case of an exception is placed in an except block. For example:

python
Copy code
try: x = int("hello") except ValueError: print("Invalid input.") # Output: Invalid input.
  • How do you perform file I/O in Python?

You perform file I/O in Python using the built-in open function and the file object it returns. The open function takes two arguments: the name of the file, and the mode in which the file should be opened. For example:

python
Copy code
# Writing to a file with open("hello.txt", "w") as file: file.write("Hello, world!") # Reading from a file with open("hello.txt", "r") as file: data = file.read() print(data) # Output: Hello, world!

    Leave a Comment


  • captcha text