Have a question?
Message sent Close

Python Interview Questions

Python is a high-level, interpreted programming language known for its readability and simplicity.

The main built-in data types include integers, floats, strings, lists, tuples, sets, and dictionaries.

A list is a mutable, ordered collection of items that can contain mixed data types.

    • tuple is an immutable, ordered collection of items, similar to a list.
    • You create a dictionary using curly braces, e.g., my_dict = {'key': 'value'}.
    • A set is an unordered collection of unique items.
    • == checks for value equality, while is checks for reference equality (identity).
    • You handle exceptions using try and except blocks.
    • A lambda function is a small anonymous function defined using the lambda keyword.

self refers to the instance of the class and is used to access instance variables and methods.

 

    • List comprehensions provide a concise way to create lists using a single line of code.

A shallow copy creates a new object but inserts references into it, while a deep copy creates a new object and recursively adds copies of nested objects.

    • Decorators are functions that modify the behavior of another function or method.
    • Generators are a way to create iterators using the yield statement, allowing lazy evaluation.
    • GIL is a mutex that protects access to Python objects, preventing multiple threads from executing Python bytecode simultaneously.
  •  

    • Use the class keyword, e.g., class MyClass: pass.
    • Modules are files containing Python code that can be imported and reused in other Python scripts.
    • __init__ is a constructor method that initializes instance variables when an object is created.
    • Some built-in functions include len(), type(), int(), str(), and print().

break exits the loop, while continue skips to the next iteration of the loop.

    • The with statement simplifies exception handling by encapsulating common preparation and cleanup tasks.
    • Metaclasses are classes of classes that define how a class behaves. They control class creation.
    • Python manages memory using automatic garbage collection.
    • Context managers are objects that manage resources, using __enter__ and __exit__ methods.
    • Monkey patching refers to modifying or extending libraries or classes at runtime.
    • Use open() to read or write files, and methods like .read(), .write(), and .close().
    • *args allows you to pass a variable number of non-keyword arguments, while **kwargs allows for variable keyword arguments.
    • pass is a null statement used as a placeholder for future code.
    • Inherit from a parent class by specifying it in parentheses, e.g., class Child(Parent):.

Types include single inheritance, multiple inheritance, and multilevel inheritance.

    • A stack is a data structure that follows the Last In First Out (LIFO) principle.
    • A queue is a data structure that follows the First In First Out (FIFO) principle.
    • Create a Node class and a LinkedList class to manage nodes.
    • A binary tree is a tree data structure in which each node has at most two children.
    • Use recursion or a stack to explore as far as possible along each branch before backtracking.
    • Use a queue to explore all neighbors at the present depth prior to moving on to nodes at the next depth level.
    • A hash table is a data structure that maps keys to values for fast lookup.
    • Use the .sort() method for in-place sorting or the sorted() function for a new sorted list.
    • A binary search is an efficient algorithm for finding an item in a sorted array, dividing the search interval in half.

Access: O(1), Search: O(n), Insertion: O(n), Deletion: O(n).

 

    • NumPy is a library for numerical computing in Python, providing support for arrays and matrices.
    • Pandas is a library for data manipulation and analysis, offering data structures like DataFrames.
    • Matplotlib is a plotting library for creating static, interactive, and animated visualizations.
    • Flask is a lightweight web framework for building web applications in Python.
    • Django is a high-level web framework that encourages rapid development and clean design.
    • TensorFlow is an open-source library for machine learning and deep learning applications.
    • Scikit-learn is a machine learning library that provides simple and efficient tools for data analysis.
    • Beautiful Soup is a library for parsing HTML and XML documents and extracting data from them.
    • OpenCV is an open-source computer vision and machine learning software library.

PyTorch is an open-source machine learning library used for applications such as computer vision and natural language processing.

 

  • Class variables are shared among all instances of the class.
  • Instance variables are unique to each instance.

Method overriding occurs when a child class provides a specific implementation of a method that is already defined in its parent class.

Python does not support method overloading in the traditional sense. However, you can achieve similar behavior using default arguments.

Abstraction refers to hiding the internal details and showing only the necessary functionality.

Encapsulation is the concept of bundling data and methods that operate on the data within a single class, and restricting access to some of the class’s components.

  • Polymorphism allows different classes to be treated as instances of the same class through inheritance.

Inheritance allows a class (child class) to inherit attributes and methods from another class (parent class).

  • Avoid reference cycles by using weak references (weakref module).
  • Use tools like gc to identify and handle garbage collection issues.
 
def reverse_string(s):
return s[::-1]
 
def is_palindrome(s):
return s == s[::-1]

def second_largest(numbers):

unique_numbers = list(set(numbers))

unique_numbers.sort()

return unique_numbers[-2]

def factorial(n):

return 1 if n == 0 else n * factorial(n – 1)

def prime_numbers(limit):

primes = []

for num in range(2, limit + 1):

for i in range(2, int(num ** 0.5) + 1):

if num % i == 0:

break

else: primes.append(num)

return primes

def longest_common_prefix(strs):

        if not strs:

            return “”

      prefix = strs[0]

      for s in strs[1:]:

                while not s.startswith(prefix):

                         prefix = prefix[:-1]

                         if not prefix:

                           return ” “

return prefix

def missing_number(arr):

n = len(arr) + 1

return n * (n + 1) // 2sum(arr)

def are_anagrams(s1, s2):

return sorted(s1) == sorted(s2)

def merge_sorted_arrays(arr1, arr2):

     return sorted(arr1 + arr2)

def remove_duplicates(lst):

return list(set(lst))

class MyClass:

def __init__(self, name):

self.name = name

class Singleton:

_instance = None

def __new__(cls):

if not cls._instance:

cls._instance = super(Singleton, cls).__new__(cls)

return cls._instance

Multiple inheritance allows a class to inherit from more than one parent class. It is implemented like this:

class A:

pass

class B:

pass

class C(A, B):

pass

Monkey patching refers to modifying or extending the behavior of libraries or classes at runtime.

Eg:

def new_method(self):

print(“Monkey patched!”)

SomeClass.method = new_method

A context manager is used to manage resources, such as file streams. It is implemented using the with statement to ensure that resources are cleaned up after use.

  • with open('file.txt', 'r') as file:
    data = file.read()

 

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

Example:

try:

x = 1 / 0

except ZeroDivisionError:

print(“Division by zero!”)

List comprehensions provide a concise way to create lists by iterating over an iterable and optionally applying a filter.

squares = [x**2 for x in range(10) if x % 2 == 0]

A lambda function is an anonymous function expressed as a single statement. It is defined using the lambda keyword.

add = lambda x, y: x + y

Talk to Our Career Expert

We'd Love to hear from you

WhatsApp