DON'T WANT TO MISS A THING?

Certification Exam Passing Tips

Latest exam news and discount info

Curated and up-to-date by our experts

Yes, send me the newsletter

Top Python Developer Interview Questions to Know | SPOTO

Whether you're preparing for your first job interview or leveling up your career, having the right preparation makes all the difference. This comprehensive resource covers the most common and challenging Interview Questions and Answers across a wide range of roles and industries — from technical positions to managerial and entry-level jobs. Browse our curated lists of Frequently Asked Interview Questions, behavioral interview questions and answers, situational interview questions, and role-specific interview prep guides designed to help you walk into any interview with confidence. Whether you're looking for IT interview questions and answers, project management interview questions, or top interview questions for freshers, our expert-reviewed content gives you real-world sample answers, proven tips, and insider strategies to help you stand out.
Make your resume stand out — at SPOTO, you can accelerate your career growth by preparing for job interviews while studying for your certification. Click Learn More to take the first step toward career advancement.
View Other Interview Questions

1
Can You Differentiate Between Wheels and Eggs?
Reference answer
The key differences between the two include: - The wheel is newer and is a standard recommendation for Python developers. - The wheel is used for packaging (distribution), while Egg is used for distribution and installation. - Wheel specifications have been versioned while Egg specifications have not. - Wheel requires PEP-376 compliance whereas Egg does not have an official PEP and uses egg.info. - Wheel enjoys robust naming conventions while Egg has limited naming conventions.
2
How do you create a diagonal matrix in NumPy?
Reference answer
You can create a diagonal matrix in NumPy using the numpy.diag() function. For example, numpy.diag([1,2,3]) creates a 3x3 diagonal matrix with the values 1, 2, and 3 on the diagonal.
Career Acceleration

Earn a certification to make your resume stand out.

According to data analysis, IT certification holders earn an annual salary that is 26% higher than that of average job seekers. At SPOTO, you have the opportunity to accelerate your career growth by pursuing certification and preparing for job interviews simultaneously.

1 100% Pass Rate
2 2 Weeks of Dump Practice
3 Pass the Certification Exam
3
What is the difference between inplace=True and inplace=False in Pandas DataFrame operations?
Reference answer
When `inplace=```True``` `, DataFrame operations modify the original DataFrame. When `inplace=```False``` ` (the default``), a new DataFrame is returned, leaving the original DataFrame unchanged.
4
5. How do you explain Python's pass-by-object-reference works?
Reference answer
The object reference is passed by value, in Python's pass by object reference. A copy of this reference is passed, when a variable is passed as a function parameter. You're actually passing the reference to the object the variable refers to, not a fresh copy of the object. Every object in Python has a unique ID, which is its memory address. Variable points to the memory address of its associated object when you create it. Passing a variable to a function transfers this reference, not the object itself. Changes inside the function affect the original object, if the object is mutable, like a list or dictionary. This is because the function and the original variable refer to the same memory location. Any change inside the function creates a new object, If the object is immutable, like an integer or string. The original remains unchanged.
5
How can elements be removed from an array in Python?
Reference answer
Array elements can be removed using pop() or remove() method. The difference between these two functions is that the former returns the deleted value whereas the latter does not. Example: a=arr.array('d', [1.1, 2.2, 3.8, 3.1, 3.7, 1.2, 4.6]) print(a.pop()) print(a.pop(3)) a.remove(1.1) print(a) Output: 4.6 3.1 array(‘d', [2.2, 3.8, 3.7, 1.2])
6
What built-in types does Python support?
Reference answer
• Number • String • Tuple • List • Dictionary • Set
7
What are unit tests in Python?
Reference answer
- Unit test is a unit testing framework of Python. - Unit testing means testing different components of software separately. Can you think about why unit testing is important? Imagine a scenario, you are building software that uses three components namely A, B, and C. Now, suppose your software breaks at a point time. How will you find which component was responsible for breaking the software? Maybe it was component A that failed, which in turn failed component B, and this actually failed the software. There can be many such combinations. - This is why it is necessary to test each and every component properly so that we know which component might be highly responsible for the failure of the software.
8
What is the role of Python in DevOps?
Reference answer
Python plays a pivotal role in the DevOps ecosystem due to its simplicity and flexibility. DevOps practices emphasize automation, continuous integration, and deployment, areas where Python excels. - Automation: Libraries and frameworks like Ansible, SaltStack, and Fabric are instrumental in automating repetitive tasks like provisioning resources, configuring servers, and deploying applications. - Scripting: Python is often the language of choice for scripting due to its readability and ease of use, ranging from small tasks like file manipulation to complex operations like network configuration. - Continuous Integration and Deployment (CI/CD): Python integrates well with CI/CD tools like Jenkins, Travis CI, and CircleCI. It can write test cases, extend functionality, and build plugins. - Infrastructure as Code (IaC): Python's ability to interact with cloud service APIs using libraries like Boto3 for AWS makes it suitable for managing infrastructure with scripts. - Monitoring and Logging: Python's support for logging and monitoring with tools like Prometheus and Graphite is essential for maintaining application health. - Security and Compliance: Security-focused libraries enable DevOps teams to integrate security measures into the development pipeline. Python's community support and extensive documentation contribute to its prominence, providing easy access to resources for finding solutions or improving processes.
9
How can you handle real-time data with Python?
Reference answer
Real-time data processing is critical in domains like finance, IoT, and social media. Key considerations and tools for handling real-time data with Python include: Asynchronous Programming: Essential for concurrent processing without blocking. Python's asyncio library provides a framework for event loop programming and managing coroutines. Websockets for Real-Time Communication: Provide a full-duplex communication channel over a single long-lived connection. Libraries like websockets facilitate development of real-time server and client applications. Message Brokers and Queuing Systems: For high-throughput data with minimal latency, use message brokers like RabbitMQ or Apache Kafka. Python interfaces well with these for efficient data distribution. Stream Processing Libraries: Libraries like Faust or Streamz are designed for building streaming applications that process large volumes of data in real-time. In-Memory Data Stores: Stores like Redis provide sub-millisecond response times. Python's redis-py library provides a simple interface. Monitoring and Performance: Use monitoring tools like Prometheus and Grafana to visualize and alert on metrics. Testing: Use pytest for writing tests and Locust for load testing to ensure reliability and performance.
10
What are some of the most commonly used built-in modules in Python?
Reference answer
Python modules are the files having python code which can be functions, variables or classes. These go by .py extension. The most commonly available built-in modules are: - os - math - sys - random - re - datetime - JSON
11
You encounter a bug in your Python code. How do you debug it effectively?
Reference answer
- Answer: I'd use the built-in Python debugger (pdb) to step through the code line by line. I'd also utilize print statements strategically, analyze error messages, and leverage IDE features like breakpoint debugging.
12
What is a dictionary and how do you access its elements?
Reference answer
- Key-value pairs where keys are unique identifiers and values can be any Python type. - Access elements by key: dict[key]
13
How do you reset the index of a DataFrame in Pandas?
Reference answer
You can reset the index of a DataFrame using the `.reset_index()` method. It will create a new DataFrame with a default integer index.
14
Write a Python code to check if a number is prime.
Reference answer
def is_prime(num): if num <= 1: return False for i in range(2, int(num ** 0.5) + 1): if num % i == 0: return False return True print(is_prime(7)) # True print(is_prime(10)) # False
15
What are functions in Python?
Reference answer
Functions in Python are reusable blocks of code that perform a specific task. They are defined using the 'def' keyword, can accept parameters, and can return values. Functions help in code modularity and organization.
16
Build on your previous function to return the largest number in the list, in addition to the sum. For the list [1, 2, 3, 4], the function should return the sum 10 and the maximum number 4. Do not use the built-in max function.
Reference answer
def sum_and_max_of_list(numbers): total = 0 max_number = numbers[0] # Assume the first number is the largest initially for number in numbers: total += number if number > max_number: max_number = number return total, max_number Explanation of solution: The function initializes two variables: total to store the sum and max_number to store the current maximum number, initially set to the first element in the list. As it iterates through the list, it adds each element to total. Simultaneously, it checks if each element is greater than the current max_number. If so, it updates max_number. It returns both the total sum and the maximum number found in the list.
17
Write a Python program to check if a number is prime.
Reference answer
a=int(input("enter number")) if a=1: for x in range(2,a): if(a%x)==0: print("not prime") break else: print("Prime") else: print("not prime") Output: enter number 3 Prime
18
Merge two sorted lists
Reference answer
# Merge list1 and list2 and return resulted list def merge_lists(lst1, lst2): index_arr1 = 0 index_arr2 = 0 index_result = 0 result = [] for i in range(len(lst1)+len(lst2)): result.append(i) # Traverse Both lists and insert smaller value from arr1 or arr2 # into result list and then increment that lists index. # If a list is completely traversed, while other one is left then just # copy all the remaining elements into result list while (index_arr1 < len(lst1)) and (index_arr2 < len(lst2)): if (lst1[index_arr1] < lst2[index_arr2]): result[index_result] = lst1[index_arr1] index_result += 1 index_arr1 += 1 else: result[index_result] = lst2[index_arr2] index_result += 1 index_arr2 += 1 while (index_arr1 < len(lst1)): result[index_result] = lst1[index_arr1] index_result += 1 index_arr1 += 1 while (index_arr2 < len(lst2)): result[index_result] = lst2[index_arr2] index_result += 1 index_arr2 += 1 return result print(merge_lists([4, 5, 6], [-2, -1, 0, 7])) Output: [-2, -1, 0, 4, 5, 6, 7] The solution above is a more intuitive way to solve this problem. Start by creating a new empty list. This list will be filled with all the elements of both lists in sorted order and returned. Then initialize three variables to zero to store the current index of each list. Then compare the elements of the two given lists at the current index of each, append the smaller one to the new list and increment the index of that list by 1. Repeat until the end of one of the lists is reached and append the other list to the merged list. Time Complexity The time complexity for this algorithm is O(n+m)O(n+m) where nn and mm are the lengths of the lists. This is because both lists are iterated over at least once. Note that this problem can also be solved by merging in place.
19
Top K Frequent Elements: How do you find the K most frequent items in a list?
Reference answer
You first count how many times each item appears using a dictionary, then you use something like a heap or sorting to pick the top K, for interviews sorting is simple to explain, but heap is better for big data, this approach avoids checking every pair and is fast enough for real use. from collections import Counter def top_k(nums, k): count = Counter(nums) return [x for x, _ in count.most_common(k)] print(top_k([1,1,1,2,2,3], 2)) # [1, 2]
20
Write a Python code to merge two dictionaries
Reference answer
dict1 = {'a': 1, 'b': 2} dict2 = {'b': 3, 'c': 4} merged = {**dict1, **dict2} print(merged) # {'a': 1, 'b': 3, 'c': 4}
21
Given a positive integer num, write a function that returns True if num is a perfect square else False.
Reference answer
This has a relatively straightforward solution. You can check if the number has a perfect square root by: - Using math.isqrt(num) to get the integer square root exactly. - Squaring it and checking if it equals the original number. - Returning the result as a boolean. Test 1 We have provided number 10 to the valid_square() function: - By taking the integer square root of the number, we get 3. - Then, take the square of 3 and get 9. - 9 is not equal to the number, so the function will return False. Test 2 We have provided number 36 to the valid_square() function: - By taking the integer square root of the number, we get 6. - Then, take the square of 6 and get 36. - 36 is equal to the number, so the function will return True. import math def valid_square(num): if num < 0: return False square = math.isqrt(num) return square * square == num valid_square(10) # False valid_square(36) # True
22
How to calculate percentiles using NumPy?
Reference answer
We can calculate percentiles with the following code import numpy as np a = np.array([1,2,3,4,5]) p = np.percentile(a, 50) #Returns 50th percentile, e.g. median print(p) Output:3
23
What is the difference between == and is operators in Python?
Reference answer
The == operator evaluates value equality by checking if the data held by two objects is equivalent, typically invoking the __eq__ method. The is operator evaluates object identity by checking if two variables reference the exact same instance in memory using the id() function. For example, list_a = [1,2,3] and list_b = [1,2,3] will return True for == but False for is because they are different objects in memory. Use == for standard equality comparisons of content. Use is exclusively for comparing against singletons, most commonly for None checks (e.g., if val is None:). Avoid using is for comparing literals like integers or strings as it relies on implementation-specific interning behavior.
24
14. What is the purpose of Python's built-in function `enumerate()`?
Reference answer
The purpose of Python's built-in function `enumerate() ` is to return an iterator object with the count value. Developers need both the index and the item value, when iterating over a sequence like a list or a string. Python offers `enumerate() ` to simplify this task, instead of manually managing an index variable. When you pass a sequence to `enumerate() `, it returns tuples. Each tuple contains the index of the item and the item itself. This makes loop constructs more readable and eliminates the need for separate index tracking. You might want to know the position of each element, when processing elements in a list. Use `enumerate() `, and the task becomes straightforward. `enumerate() ` enhances code clarity and reduces the likelihood of errors by providing an elegant way to track element indices while iterating over sequences. It's an essential tool for any Python developer aiming to write concise and readable code.
25
Write a Python code to find the GCD of two numbers
Reference answer
def gcd(a, b): while b: a, b = b, a % b return a print(gcd(48, 18)) # 6
26
Write a Python function to compute the Least Common Multiple (LCM) of two numbers.
Reference answer
Sample Answer: The least common multiple (LCM) can be computed using the greatest common divisor (GCD), which you can get from Python's 'math.gcd()' function. Here is an example of how to write a Python function to compute the least common multiple (LCM) of two numbers: from math import gcd def lcm(a, b): return abs(a * b) // gcd(a, b)
27
Explain the difference between a list and a tuple in Python.
Reference answer
While both are collection data types, lists are mutable (can be changed), and tuples are immutable (cannot be changed). Lists use square brackets [], and tuples use parentheses ().
28
Explain Python's enumerate() function.
Reference answer
The enumerate() function adds an index to an iterable, returning tuples of the index and value. Example: fruits = ['apple', 'banana', 'cherry'] for index, fruit in enumerate(fruits): print(index, fruit) Output: 0 apple 1 banana 2 cherry
29
How can you work with binary data in Python, and what is the struct module used for?
Reference answer
The `struct` module is used to pack and unpack binary data into``/``from Python objects, enabling you to work with binary data formats like network protocols and file formats.
30
What are effective techniques for debugging complex Python code?
Reference answer
Effective techniques include using built-in debuggers such as pdb, logging key events and variables, writing minimal reproducible test cases, utilizing IDE debugging tools, and exploiting tracebacks to locate issues efficiently.
31
How do you integrate AI/ML models into your automation workflows?
Reference answer
- Answer: Discuss using libraries like TensorFlow, PyTorch, and Scikit-learn for model training and deployment. Mention techniques like model prediction within automation tasks, anomaly detection, and automated parameter tuning. - Example (Model Prediction in Selenium): import joblib model = joblib.load('model.pkl') prediction = model.predict([[feature1, feature2]])
32
Print all Fibonacci numbers up to a given number
Reference answer
def fibonacci_up_to(n): a, b = 0, 1 while a <= n: print(a) a, b = b, a + b
33
What is the use of decorators in Python, and provide an example of a decorator function.
Reference answer
Decorators in Python are used to modify the behavior of functions or methods. They are often used for logging, authentication, and memoization. Here's an example of a simple decorator to measure the execution time of a function: import time def timing_decorator(func): def wrapper(*args, **kwargs): start_time = time.time() result = func(*args, **kwargs) end_time = time.time() print(f;Execution time: {end_time – start_time} seconds;) return result return wrapper @timing_decorator def slow_function(): time.sleep(3) print(Function executed.;) slow_function()
34
Write a Python program to determine if a year is a leap year.
Reference answer
def is_leap_year(year): return (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0) print(is_leap_year(2024)) # True print(is_leap_year(2023)) # False
35
How do you make a Python script executable on Linux/macOS?
Reference answer
To make a Python script executable, you first add a shebang line at the top so the system knows how to run it, then you give it execute permission using the chmod command, after that you can run it like a normal command without writing python before it, this is very common in automation scripts and small tools, and it makes the script feel like a real system command. #!/usr/bin/env python3 print("Hello from script") chmod +x myscript.py ./myscript.py
36
Write a Python function to check if a number is an Armstrong number.
Reference answer
Solution: def is_armstrong(number): # Convert number to string to get its length num_str = str(number) # Get the number of digits num_digits = len(num_str) # Initialize sum armstrong_sum = 0 # Calculate the sum of digits raised to the power of the number of digits for digit in num_str: armstrong_sum += int(digit) ** num_digits # Check if the sum is equal to the original number return armstrong_sum == number # Example usage input_number = 153 if is_armstrong(input_number): print(input_number, "is an Armstrong number.") else: print(input_number, "is not an Armstrong number.") Output: 153 is an Armstrong number.
37
What does the Python break statement do?
Reference answer
The Python break statement stops a loop statement and transfers execution of the code to the statement after the loop.
38
What is the difference between merge, join, and concatenate?
Reference answer
Merge Merge two DataFrames named series objects using the unique column identifier. It requires two DataFrame, a common column in both DataFrame, and “how” you want to join them together. You can left, right, outer, inner, and cross join two data DataFrames. By default, it is an inner join. pd.merge(df1, df2, how='outer', on='Id') Join Join the DataFrames using the unique index. It requires an optional on argument that can be a column or multiple column names. By default, the join function performs a left join. df1.join(df2) Concatenate Concatenate joins two or multiple DataFrames along a particular axis (rows or columns). It doesn't require an on argument. pd.concat(df1,df2) - join(): combines two DataFrames by index. - merge(): combines two DataFrames by the column or columns you specify. - concat(): combines two or more DataFrames vertically or horizontally.
39
What is the purpose of the .sample() method in Pandas?
Reference answer
The `.sample()` method is used to select a random sample of rows or columns from a DataFrame, which can be useful for data exploration and testing.
40
What are Python namespaces? Why are they used?
Reference answer
A namespace in Python ensures that object names in a program are unique and can be used without any conflict. Python implements these namespaces as dictionaries with 'name as key' mapped to a corresponding 'object as value'. This allows for multiple namespaces to use the same name and map it to a separate object. A few examples of namespaces are as follows: - Local Namespace includes local names inside a function. the namespace is temporarily created for a function call and gets cleared when the function returns. - Global Namespace includes names from various imported packages/ modules that are being used in the current project. This namespace is created when the package is imported in the script and lasts until the execution of the script. - Built-in Namespace includes built-in functions of core Python and built-in names for various types of exceptions. The lifecycle of a namespace depends upon the scope of objects they are mapped to. If the scope of an object ends, the lifecycle of that namespace comes to an end. Hence, it isn't possible to access inner namespace objects from an outer namespace.
41
How will you delete indices, rows and columns from a dataframe?
Reference answer
To delete an Index: - Execute del df.index.name for removing the index by name. - Alternatively, the df.index.name can be assigned to None. - For example, if you have the below dataframe: Column 1 Names John 1 Jack 2 Judy 3 Jim 4 - To drop the index name "Names": df.index.name = None # Or run the below: # del df.index.name print(df) Column 1 John 1 Jack 2 Judy 3 Jim 4 To delete row/column from dataframe: - drop() method is used to delete row/column from dataframe. - The axis argument is passed to the drop method where if the value is 0, it indicates to drop/delete a row and if 1 it has to drop the column. - Additionally, we can try to delete the rows/columns in place by setting the value of inplace to True. This makes sure that the job is done without the need for reassignment. - The duplicate values from the row/column can be deleted by using the drop_duplicates() method.
42
How do you work with regular expressions (regex) in Python, and what are some common use cases for regex?
Reference answer
Python provides the `re` module for working with regular expressions. Common use cases include text parsing and pattern matching.
43
Extend the basic Flask application from Question 1 to render an HTML template when accessing the '/' route. Assume the HTML file is named index.html and located in a templates folder. The template should display "Welcome to Flask with Templates!".
Reference answer
# Assuming index.html is in the 'templates' folder from flask import Flask, render_template app = Flask(__name__) @app.route('/') def home(): return render_template('index.html') # index.html content: # # Flask Template #

Welcome to Flask with Templates!

# Explanation of solution: The render_template function from Flask is used to render an HTML template. The home view function now returns render_template('index.html'), rendering the index.html file from the templates directory. The index.html file contains basic HTML to display a welcome message.
44
Is Python a case sensitive language?
Reference answer
Yes. Python is a case sensitive language.
45
What are break and continue statements in Python?
Reference answer
The break statement is used to exit a loop prematurely, while the continue statement is used to skip the current iteration and proceed to the next one in a loop.
46
How to add and remove values to a Python array?
Reference answer
To add values to a Python array (e.g., using the array module or list), use the append() method for single elements or extend() for multiple. To remove values, use remove() to delete a specific element or pop() to remove by index.
47
How Do You Identify Bugs in Your Code?
Reference answer
Developers usually use Pychecker and Pylint. It is a good Python coding interview question to check the basic knowledge of tools and bug checks.
48
How do you handle merges and joins between two DataFrames based on specific conditions?
Reference answer
- Use merge with appropriate join types (inner, left, right, outer) and merge keys.
49
Explain the purpose of the NumPy library in Python.
Reference answer
NumPy is a library for numerical computing in Python. It provides support for large, multi-dimensional arrays and matrices, along with mathematical functions to operate on them.
50
Check if a Python string contains another string
Reference answer
There are a couple ways to check this. For this post, we'll look at the find method. The find method checks if the string contains a substring. If it does, the method returns the starting index of a substring within the string; otherwise, it returns -1. The general syntax is: string.find(substring) a_string="Python Programming" substring1="Programming" substring2="Language" print("Check if "+a_string+" contains "+substring1+":") print(a_string.find(substring1)) print("Check if "+a_string+" contains "+substring2+":") print(a_string.find(substring2)) Output: Check if Python Programming contains Programming: 7 Check if Python Programming contains Language: -1 The other two notable methods for checking if a string contains another string are to use in operator or use the count method.
51
What is PIP ? Name some common PIP Command.
Reference answer
PIP (Python Package Installer) is the default package manager for Python. It is a command-line tool that allows you to easily install, manage, and uninstall Python packages from the Python Package Index (PyPI) or other package repositories. Some Common PIP Command are: - pip install package_name: Installs a Python package. - pip uninstall package_name: Uninstalls a Python package. - pip list: Lists all installed packages. - pip freeze > requirements.txt: Exports a list of installed packages and their versions to a requirements.txt file. - pip install -r requirements.txt: Installs packages listed in a requirements.txt file.
52
What are Exception Groups in Python?
Reference answer
Exception Groups are a feature introduced in Python 3.11 that allow multiple exceptions to be grouped together and handled in a structured way. They are particularly useful when several operations may fail independently, such as in concurrent or asynchronous programs. ExceptionGroup class is used to combine multiple exceptions into a single object and the except* syntax is used to handle specific exception types within the group. try: raise ExceptionGroup( "Example ExceptionGroup", [ TypeError("Example TypeError"), ValueError("Example ValueError"), KeyError("Example KeyError"), AttributeError("Example AttributeError"), ] ) except* TypeError: print("Handled TypeError") except* ValueError: print("Handled ValueError") except* (KeyError, AttributeError): print("Handled KeyError and AttributeError") Output Handled TypeError Handled ValueError Handled KeyError and AttributeError
53
Count the occurrences of a character in a string
Reference answer
def count_char(s, c): return s.count(c)
54
How do you comment out multiple lines of code in Python?
Reference answer
You can use triple-quoted strings (''' or """) to comment out multiple lines of code, although using the # symbol for each line is more common.
55
How do you implement a binary tree and perform an in-order traversal?
Reference answer
Sample Answer: A binary tree is a hierarchical structure in which each node can have at most two children, referred to as the left and right child. In-order traversal is a depth-first traversal method that visits the left subtree, the root node, and then the right subtree recursively, resulting in the nodes being processed in ascending order for a binary search tree. Here's how you can implement a binary tree and perform an in-order traversal in Python: class Node: def __init__(self, key): self.left = None self.right = None self.value = key def in_order_traversal(root): if root: in_order_traversal(root.left) #visit the left subtree print(root.value, end=' ') #visit root in_order_traversal(root.right) #visit right subtree
56
What are Dict and List comprehensions?
Reference answer
Python comprehensions, like decorators, are syntactic sugar constructs that help build altered and filtered lists, dictionaries, or sets from a given list, dictionary, or set. Using comprehensions saves a lot of time and code that might be considerably more verbose (containing more lines of code). Let's check out some examples, where comprehensions can be truly beneficial: - Performing mathematical operations on the entire list my_list = [2, 3, 5, 7, 11] squared_list = [x**2 for x in my_list] # list comprehension # output => [4 , 9 , 25 , 49 , 121] squared_dict = {x:x**2 for x in my_list} # dict comprehension # output => {11: 121, 2: 4 , 3: 9 , 5: 25 , 7: 49} - Performing conditional filtering operations on the entire list my_list = [2, 3, 5, 7, 11] squared_list = [x**2 for x in my_list if x%2 != 0] # list comprehension # output => [9 , 25 , 49 , 121] squared_dict = {x:x**2 for x in my_list if x%2 != 0} # dict comprehension # output => {11: 121, 3: 9 , 5: 25 , 7: 49} - Combining multiple lists into one Comprehensions allow for multiple iterators and hence, can be used to combine multiple lists into one. a = [1, 2, 3] b = [7, 8, 9] [(x + y) for (x,y) in zip(a,b)] # parallel iterators # output => [8, 10, 12] [(x,y) for x in a for y in b] # nested iterators # output => [(1, 7), (1, 8), (1, 9), (2, 7), (2, 8), (2, 9), (3, 7), (3, 8), (3, 9)] - Flattening a multi-dimensional list A similar approach of nested iterators (as above) can be applied to flatten a multi-dimensional list or work upon its inner elements. my_list = [[10,20,30],[40,50,60],[70,80,90]] flattened = [x for temp in my_list for x in temp] # output => [10, 20, 30, 40, 50, 60, 70, 80, 90] Note: List comprehensions have the same effect as the map method in other languages. They follow the mathematical set builder notation rather than map and filter functions in Python.
57
What is the purpose of the super() function in Python?
Reference answer
The `super()` function is used to call a method from a parent or superclass. It is often used in the constructor (`__init__`) of a subclass to call the constructor of the parent class.
58
3.What are Python's built-in types?
Reference answer
Python's built in types are numerics, sequences, mappings, classes, instances and exceptions. Built in types are categorized in main groups: mutable and immutable. Immutable types are listed as follows. - Integers (int): Whole numbers, both positive and negative. - Floats (float): Decimal numbers, representing real numbers. - Complex (complex): Represents complex numbers. - Strings (str): Sequence of Unicode characters. - Tuples (tuple): Ordered collection of items, which can be of mixed types. - Booleans (bool): Represents True or False values. - Frozensets (frozenset): Unmodifiable sets. Mutable types are listed below. - Lists (list): Ordered collection of items. - Sets (set): Unordered collection of unique items. - Dictionaries (dict): Key-value pairs. - Bytes (bytes): Sequence of bytes. - ByteArrays (bytearray): Arrays of bytes. - MemoryViews (memoryview): View object that exposes an array's buffer interface.
59
Given a 2D NumPy array, write a function to select and return a subarray consisting of the first two rows and the last two columns. Explain how slicing affects memory usage and the relationship between the original and sliced arrays.
Reference answer
import numpy as np def select_subarray(array): # Selecting the first two rows and the last two columns subarray = array[:2, -2:] return subarray # Slicing creates a view on the original array, not a copy. # Changes to the subarray will affect the original array and vice versa. Explanation of solution: The function select_subarray demonstrates slicing to extract a specific part of an array. Rather than making copies, slicing creates a view, meaning the subarray shares data with the original array. This is memory efficient but requires care; because they reference the same data, modifying one affects the other.
60
How do you calculate the power of a number using recursion?
Reference answer
Sample Answer: Calculating the power of a number recursively involves multiplying the base by itself a specified number of times, which is determined by the exponent. The recursion continues until the exponent reaches zero, at which point the result is 1, as any number raised to the power of zero is defined as 1. Here's the code: def power(base, exp): if exp == 0: return 1 return base * power(base, exp - 1)
61
How do you access values in a dictionary?
Reference answer
You can access values by specifying the key in square brackets, like this: my_dict = {"name": "Alice", "age": 30} print(my_dict["name"]) # Output: Alice
62
What is the Use of Break, Continue, and Pass?
Reference answer
The primary use of these statements is given below: - Break: Terminates the loop and moves to the next statement. - Continue: Rejects the subsequent statements of a loop and reverts the control to the top. - Pass: Bypasses a block of code that is needed for syntax purposes.
63
Find the sum of all elements in a list
Reference answer
def sum_list(lst): return sum(lst)
64
How to save an image locally from a URL using Python?
Reference answer
We will use the following code to save an image locally from an URL address import urllib.request urllib.request.urlretrieve("URL", "local-filename.jpg")
65
How do you handle exceptions in Python?
Reference answer
Exceptions in Python are handled using the try, except, finally, and raise keywords.
66
What is data enrichment in data processing?
Reference answer
Data enrichment is the process of enhancing existing data by adding new relevant information from external sources. Example: If you have a DataFrame with customer IDs, you can enrich it by merging with another DataFrame containing customer demographics.
67
Describe the Differences Between Shallow and Deep Copy When Using Python.
Reference answer
Deep copy creates more copies recursively and changes in the copies will not affect the original object. A shallow copy will not create the copy itself and any change in the copy will also make a change in the original object.
68
Write a Program to match a string that has the letter 'a' followed by 4 to 8 'b's.
Reference answer
We can use the re module of python to perform regex pattern comparison here. import re def match_text(txt_data): pattern = 'ab{4,8}' if re.search(pattern, txt_data): #search for pattern in txt_data return 'Match found' else: return('Match not found') print(match_text("abc")) #prints Match not found print(match_text("aabbbbbc")) #prints Match found
69
What is the difference between a shallow copy and a deep copy of an object in Python?
Reference answer
In Python, a shallow copy of an object creates a new object but does not create new copies of the elements inside the object. Instead, it copies references to the original elements. A deep copy, on the other hand, creates a new object and recursively copies all the elements and their contents, resulting in an independent copy of the original object.
70
What is the purpose of the PYTHONPATH variable?
Reference answer
PYTHONPATH is an environmental variable that will tell the operating system where to find Python libraries. This will ensure that your Operating System calls the correct installation of Python on the computer.
71
What are *args and **kwargs in Python?
Reference answer
*args and **kwargs are special syntaxes used in function definitions to handle a variable number of arguments. *args collects extra positional arguments into a tuple using the single asterisk unpacking operator. It is ideal for functions where the number of inputs is unknown at runtime. **kwargs captures named (keyword) arguments not explicitly defined in the parameter list into a dictionary using the double asterisk operator. It is widely used in class inheritance and decorators. Python requires a specific order in function signatures: standard positional arguments, *args, keyword-only arguments, **kwargs. A bare * can also force all subsequent arguments to be keyword-only.
72
What is monkey patching in Python?
Reference answer
Monkey patching refers to dynamically modifying or extending a module or class at runtime. It is often used to change behavior without altering the original source code. Example: import some_module def new_method(): return "Patched!" some_module.original_method = new_method
73
Explain the difference between "is" and "==" in Python.
Reference answer
"==" checks if two variables have the same value, while "is" checks if two variables reference the exact same memory location (object identity).
74
Explain the key data structures in Pandas: Series and DataFrame.
Reference answer
- Series: One-dimensional labeled array; efficient for holding ordered data. - DataFrame: Two-dimensional labeled data structure with rows and columns; ideal for tabular data.
75
How would you implement an LRU Cache in Python?
Reference answer
Python provides a built-in functools.lru_cache decorator to implement an LRU (Least Recently Used) cache. Alternatively, you can create one manually using the OrderedDict from collections. Example using functools: from functools import lru_cache @lru_cache(maxsize=3) def add(a, b): return a + b print(add(1, 2)) # Calculates and caches result print(add(1, 2)) # Retrieves result from cache
76
What's the difference between shallow copy and deep copy?
Reference answer
A shallow copy copies only the outer object, so inner objects are still shared, while a deep copy copies everything fully, this matters when your data has nested lists or dicts, because changing inner data in a shallow copy also changes the original. import copy a = [[1, 2], [3, 4]] b = copy.copy(a) b[0][0] = 99 print(a) # changed c = copy.deepcopy(a) c[0][0] = 50 print(a) # unchanged
77
How does Python Flask handle database requests?
Reference answer
Python Flask handles database requests through extensions like Flask-SQLAlchemy, which provides an ORM for database interactions. It allows defining models, querying data, and handling requests via routes, often using a SQLite or PostgreSQL backend.
78
How does Python handle memory management, and what role does garbage collection play?
Reference answer
Python manages memory allocation and deallocation automatically using a private heap, where all objects and data structures are stored. The memory management process is handled by Python's memory manager, which optimizes memory usage, and the garbage collector, which deals with unused or unreferenced objects to free up memory. Garbage collection in Python uses reference counting as well as a cyclic garbage collector to detect and collect unused data. When an object has no more references, it becomes eligible for garbage collection. The gc module in Python allows you to interact with the garbage collector directly, providing functions to enable or disable garbage collection, as well as to perform manual collection.
79
What is PythonPath ?
Reference answer
PYTHONPATH is an environment variable in Python that tells the interpreter where to look for Python modules and packages. It is a list of directory paths separated by colons (on Unix-based systems) or semicolons (on Windows). When you import a module or package, Python searches for it in the directories listed in PYTHONPATH. It allows you to specify additional directories outside the default ones where your Python code resides, enabling easy access to custom modules or packages.
80
Write Python code to remove duplicate items from a list.
Reference answer
res = [] [res.append(x) for x in test_list if x not in res]
81
How can you reverse a list in Python?
Reference answer
You can reverse a list using the reverse() method or by using slicing with [::-1]. my_list = [1, 2, 3, 4] my_list.reverse() # my_list becomes [4, 3, 2, 1] reversed_list = my_list[::-1] # Creates a new reversed list
82
Explain what's Flask and its benefits.
Reference answer
Flask is a lightweight web framework for Python that allows developers to build web applications quickly and with minimal code. Its benefits include simplicity, flexibility, extensive documentation, and support for extensions for added functionality.
83
How can you handle and raise custom exceptions in Python?
Reference answer
To handle custom exceptions in Python, you can create your own exception class by inheriting from the Exception class. Here's an example of raising and handling a custom exception: class CustomError(Exception): pass def example_function(x): if x < 0: raise CustomError(Input should be a positive number.;) return x * 2 try: result = example_function(-5) except CustomError as e: print(f;Error: {e};)
84
How do you manage dependencies in a Python project, and what is the significance of a requirements.txt file?
Reference answer
I use virtual environments to isolate project dependencies and maintain a requirements.txt file to specify package versions. This ensures reproducibility and avoids conflicts.
85
What is pickling and unpickling in Python?
Reference answer
Pickling is the process of converting any Python object into a string representation. Unpickling is picking the object out of the string representation.
86
Use decorators to build a name directory. Given information about N people (first name, last name, age, and sex), print their names in a specific format (Mr. or Ms. based on sex) sorted by their age in ascending order.
Reference answer
Sample Input: 3 Mike Thomson 20 M Robert Bustle 32 M Andria Bustle 30 F Sample Output: Mr. Mike Thomson Ms. Andria Bustle Mr. Robert Bustle Concept: For sorting a nested list based on some parameter, you can use the itemgetter library.
87
What are decorators in Python?
Reference answer
Decorators in Python are a design pattern that allows you to add new functionality to an existing object without modifying its structure. They are commonly used to extend the behavior of functions or methods. You can read more about how to use Python decorators in a separate guide. Take this example: import functools def my_decorator(func): @functools.wraps(func) # preserves __name__, __doc__, etc. 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(): print("Hello!") say_hello() # Output: # Something is happening before the function is called. # Hello! # Something is happening after the function is called.
88
Describe data manipulation techniques in Pandas for cleaning and filtering data.
Reference answer
- Handling missing values (fillna, dropna), selection (loc, iloc), indexing and slicing, filtering with conditions (query, mask).
89
How do you get the MAC address of a network interface in Python?
Reference answer
You can use the getmac module in Python to get the MAC address of a network interface.
90
What are list comprehensions, and how do they work in Python?
Reference answer
List comprehensions are concise ways to create lists in Python. They consist of an expression followed by at least one `for` clause and zero or more `if` clauses to filter elements.
91
What is a Python dictionary?
Reference answer
A Python dictionary is one of the standard data structures in Python. It is an unordered collection of elements, acting as a hash-table. These elements are stored within key-value pairs. Dictionaries are indexed by keys. # Python dictionary dict={'first':'Bob', 'last':'Smith'}
92
What is __init__ in Python?
Reference answer
__init__ is a method or constructor in Python. This method is automatically called to allocate memory when a new object/ instance of a class is created. All classes have the __init__ method. Here is an example of how to use it. class Employee: def __init__(self, name, age,salary): self.name = name self.age = age self.salary = 20000 E1 = Employee("XYZ", 23, 20000) # E1 is the instance of class Employee. #__init__ allocates memory for E1. print(E1.name) print(E1.age) print(E1.salary) Output: XYZ 23 20000
93
What is the purpose of the PYTHONSTARTUP variable?
Reference answer
This variable contains the path of an initialization file that houses Python source code. It executes each time the Python interpreter starts.
94
What is a negative index in Python?
Reference answer
While positive indices begin with position 0 and follow with 1, 2, etc., negative indices end with -1. -2, etc.; -3 is the position before that, and so on. Negative indexes can access elements in a Python list from the end of the list rather than from the beginning.
95
Write a Python function to reverse a string.
Reference answer
Sample Answer: This function, named reverse_string, takes a single string as input and uses Python's slicing feature to return the string in reverse order. Slicing allows for concise manipulation of strings, making it easy to reverse them with just one line of code. Here is a sample of how to write a Python function to reverse a string. def reverse_string(s): return s[::-1]
96
What is slicing in Python?
Reference answer
Slicing is taking parts of strings, arrays, tuples, and lists. Its syntax is [start : stop : step].
97
Have you worked on any machine learning or data science projects in Python? Can you discuss a specific project and the libraries you used?
Reference answer
Yes, I've worked on a sentiment analysis project using TensorFlow and NLTK. We used pre-trained models and fine-tuned them for our specific task.
98
Is Python Case-Sensitive?
Reference answer
Yes, Python is a case-sensitive language, which means that it treats uppercase and lowercase levels differently.
99
How do you read command-line arguments in Python?
Reference answer
You can read command-line arguments using the sys.argv list, where the first value is the script name and the rest are the arguments passed by the user, this is useful for simple scripts like file converters or backup tools, but it does not give validation or help messages, it is best for small and quick scripts. import sys print("Script name:", sys.argv[0]) print("Arguments:", sys.argv[1:]) Run like: python test.py file.txt 123
100
What is the difference between {} dictionary and "OrderedDict"?
Reference answer
OrderedDict maintains the insertion order. In whatever order all the key value pairs added to the dictionary will be maintained and that cannot be possible with the regular dictionary.
101
What is the GIL, and how does it affect CPU-bound and I/O-bound tasks differently?
Reference answer
The GIL (``Global Interpreter Lock``) affects CPU``-``bound tasks by limiting multi``-``threading performance but has less impact on I``/``O``-``bound tasks``.
102
In an Interview how do we explain why we chose Python ?
Reference answer
Due to its clean, simple and small syntax with Wide variety Libraries Support makes Python easy – to – learn language. It is Dynamically Typed Languages which makes it more easier language to understand.
103
What is PEP 8?
Reference answer
PEP stands for Python Enhancement Proposal. It is a set of rules that specify how to format Python code for maximum readability.
104
83. How do you explain the MVC architecture in web development?
Reference answer
MVC (Model-View-Controller) is a design pattern used in web development to separate an application's data, presentation, and control flow. In the context of Python, frameworks like Django and Flask implement this pattern, helping developers organize their code effectively. The Model deals with data and the business logic. It interacts with the database and updates the View whenever the data changes. The View is what the user interacts with; it displays data to the user and sends user commands to the Controller. The Controller receives these commands, processes the request, and updates the Model and View accordingly. Using MVC ensures a clear separation of concerns, making it easier to maintain and scale Python web applications.
105
Describe Python's slicing technique.
Reference answer
Slicing allows you to extract a portion of a sequence (like a list or string). Using the syntax sequence[start:stop:step], you can extract elements.
106
What are regular expressions, and how are they used in Python?
Reference answer
Regular expressions (regex) are patterns used for searching and manipulating text. Python's re module provides functions for working with regular expressions.
107
Write a Python program to find the maximum of three numbers
Reference answer
def max_of_three(a, b, c): return max(a, b, c) print(max_of_three(1, 2, 3)) # 3
108
Write a program to find the intersection of two sets.
Reference answer
Sample Answer: Set intersection finds the common elements between two sets. To find the intersection of two sets, you can write your code like this: def intersection(set1, set2): return set1 & set2
109
What are profiling tools in Python and why are they useful?
Reference answer
Profiling tools (like cProfile) help measure code performance and identify bottlenecks. Example: import cProfile def my_func(): total = 0 for i in range(1000): total += i return total # Profile the function cProfile.run('my_func()')
110
What is the significance of negative indices in Python?
Reference answer
-1 is the last negative index, while -2 is the second last and so on. It is mainly used to traverse the element backward.
111
Write Python code for list and string manipulation operations.
Reference answer
Solution: # List manipulation my_list = [1, 2, 3, 4, 5] # Append an element to the list my_list.append(6) print("After appending 6:", my_list) # Remove an element from the list my_list.remove(3) print("After removing 3:", my_list) # Access elements by index print("Element at index 2:", my_list[2]) # String manipulation my_string = "Hello, World!" # Split the string into a list of words words = my_string.split() print("Split string into words:", words) # Join elements of a list into a single string new_string = "-".join(words) print("Joined words with '-':", new_string) # Convert string to uppercase upper_string = my_string.upper() print("Uppercase string:", upper_string) # Replace a substring replaced_string = my_string.replace("World", "Universe") print("After replacing 'World' with 'Universe':", replaced_string) Output: After appending 6: [1, 2, 3, 4, 5, 6] After removing 3: [1, 2, 4, 5, 6] Element at index 2: 4 Split string into words: ['Hello,', 'World!'] Joined words with '-': Hello,-World! Uppercase string: HELLO, WORLD! After replacing 'World' with 'Universe': Hello, Universe!
112
How do you stay updated with the latest trends and advancements in Python automation?
Reference answer
- Answer: Mention attending conferences, reading blogs and documentation, participating in online communities, contributing to open-source projects, and exploring new frameworks and libraries.
113
What is an accumulator?
Reference answer
Accumulator is a variable, which is generally used in the loop to accumulate the values in each iteration. E.g. if you want to add all the values in a list [1,2,3,4] . Then, you will be creating an accumulator which will hold the sum till the previous iteration.
114
How do you read/write JSON and CSV files in Python?
Reference answer
Python has built-in modules for JSON and CSV, for JSON you use the json module to load and dump data, and for CSV you use the csv module, these are very common in automation, data cleaning, and reports, and they are easy to use for basic files. import json data = {"name": "Aakash", "age": 20} with open("data.json", "w") as f: json.dump(data, f) with open("data.json") as f: print(json.load(f)) import csv with open("data.csv", "w", newline="") as f: writer = csv.writer(f) writer.writerow(["name", "age"]) writer.writerow(["Aakash", 20])
115
What does the Python dir() function do?
Reference answer
The Python dir() function will return a list of methods and attributes from the object you call it with.
116
What is the ternary operator?
Reference answer
The ternary operator is a way of writing conditional statements in Python. As the name ternary suggests, this Python operator consists of three operands. Note: The ternary operator can be thought of as a simplified, one-line version of the if-else statement to test a condition. Syntax The three operands in a ternary operator include: - condition: A boolean expression that evaluates to either true or false. - true_val : A value to be assigned if the expression is evaluated to true. - false_val : A value to be assigned if the expression is evaluated to false. var = true_val if condition else false_val The variable var on the left-hand side of the = (assignment) operator will be assigned: - value1 if the booleanExpression evaluates totrue . - value2 if the booleanExpression evaluates tofalse . Example # USING TERNARY OPERATOR to_check = 6 msg = "Even" if to_check%2 == 0 else "Odd" print(msg) # USING USUAL IF-ELSE msg = "" if(to_check%2 == 0): msg = "Even" else: msg = "Odd" print(msg) Output: Even Even Explanation The above code is using the ternary operator to find if a number is even or odd. - msg will be assigned “even” if the condition (to_check % 2 == 0) istrue . - msg will be assigned “odd” if the condition (to_check % 2 == 0) isfalse .
117
How does Python handle memory management?
Reference answer
Python has a built-in garbage collector that recycles and reclaims memory from objects no longer in use. It primarily uses reference counting to manage memory.
118
What is the difference between Python 2 and Python 3?
Reference answer
Python 3 introduced several significant changes, including print() as a function, Unicode as the default string type, and improved syntax. It is not backward compatible with Python 2.
119
Create a function to iterate through a nested dictionary of arbitrary depth
Reference answer
def iterate_nested_dict(d, path=''): for key, value in d.items(): new_path = f'{path}.{key}' if path else key if isinstance(value, dict): iterate_nested_dict(value, new_path) else: print(f'{new_path}: {value}')
120
What is the difference between append() and extend() methods in Python lists?
Reference answer
Both append() and extend() are list methods in Python. The append() method adds a single element to the end of the list, whereas the extend() method takes an iterable (e.g., list, tuple, string) and appends each element from the iterable to the list.
121
Multiple Choice Question: Which of the following is correct to create a dictionary? a) d = {1,2,3} b) d = {1:'a', 2:'b'} c) d = {1, 'a': 2, 'b'} d) d = {}
Reference answer
Answer: b, c & d. Dictionaries are created by specifying keys and values.
122
What is indentation in Python, and why is it important?
Reference answer
Indentation refers to the spaces at the beginning of a code line. Where in other programming languages the indentation in code is for readability only, the indentation in Python is very important. Python uses indentation to indicate a block of code. Python will give you an error if you skip the indentation.
123
What are Built-in data types in Python?
Reference answer
The following are the standard or built-in data types in Python: - Numeric: The numeric data type in Python represents the data that has a numeric value. A numeric value can be an integer, a floating number, a Boolean, or even a complex number. - Sequence Type: The sequence Data Type in Python is the ordered collection of similar or different data types. There are several sequence types in Python like String, List, Tuple, range - Mapping Types: In Python, hashable data can be mapped to random objects using a mapping object. There is currently only one common mapping type, the Dictionary and mapping objects are mutable. - Set Types: In Python, a Set is an unordered collection of data types that is iterable, mutable and has no duplicate elements. The order of elements in a set is undefined though it may consist of various elements.
124
Can you find the maximum single sell profit?
Reference answer
You are provided with the list of stock prices, and you have to return the buy and sell price to make the highest profit. Note: We have to make maximum profit from a single buy/sell, and if we can't make a profit, we have to reduce our losses. Example 1: stock_price = [8, 4, 12, 9, 20, 1], buy = 4, and sell = 20. Maximizing the profit. Example 2: stock_price = [8, 6, 5, 4, 3, 2, 1], buy = 6, and sell = 5. Minimizing the loss. Solution: - We will calculate the global profit by subtracting global sell (the first element in the list) from current buy (the second element in the list). - Run the loop for the range of 1 to the length of the list. - Within the loop, calculate the current profit using list elements and current buy value. - If the current profit is greater than the global profit, change the global profit with the current profit and global sell to the i element of the list. - If the current buy is greater than the current element of the list, change the current buy with the current element of the list. - In the end, we will return global buy and sell value. To get global buy value, we will subtract global sell from global profit. The question is a bit tricky, and you can come up with your unique algorithm to solve the problems. def buy_sell_stock_prices(stock_prices): current_buy = stock_prices[0] global_sell = stock_prices[1] global_profit = global_sell - current_buy for i in range(1, len(stock_prices)): current_profit = stock_prices[i] - current_buy if current_profit > global_profit: global_profit = current_profit global_sell = stock_prices[i] if current_buy > stock_prices[i]: current_buy = stock_prices[i] return global_sell - global_profit, global_sell stock_prices_1 = [10,9,16,17,19,23] buy_sell_stock_prices(stock_prices_1) # (9, 23) stock_prices_2 = [8, 6, 5, 4, 3, 2, 1] buy_sell_stock_prices(stock_prices_2) # (6, 5)
125
How would you check if a key exists in a Python dictionary?
Reference answer
It is a safe practice to check whether or not the key exists in the dictionary prior to extracting the value of that key. For that purpose, Python offers two built-in functions: has_key() The has_key method returns true if a given key is available in the dictionary; otherwise, it returns false. Fruits = {'a': "Apple", 'b':"Banana", 'c':"Carrot"} key_to_lookup = 'a' if Fruits.has_key(key_to_lookup): print "Key exists" else: print "Key does not exist" Output: Key exists - if-in statement This approach uses the if-in statement to check whether or not a given key exists in the dictionary. Fruits = {'a': "Apple", 'b':"Banana", 'c':"Carrot"} key_to_lookup = 'a' if key_to_lookup in Fruits: print "Key exists" else: print "Key does not exist" Output: Key exists
126
What is a generator in Python? How is it different from a regular function?
Reference answer
A generator is a special type of function in Python that returns an iterator object, which can be iterated over using a for loop. The key difference between a generator and a regular function is that a generator can yield values one at a time, whereas a regular function returns all values at once. This makes generators more memory-efficient, as they do not need to generate all values at once and store them in memory.
127
Explain your approach to handling dynamic web elements when automating browser interactions.
Reference answer
- Answer: Mention using WebDriverWait with expected conditions like presence of element, using CSS selectors with unique identifiers, and leveraging libraries like Selenium DevTools for dynamic element analysis.
128
What constitutes a good unit test and what a functional one?
Reference answer
A good unit test is isolated, tests a single unit of code (e.g., a function or method), is fast, deterministic, and covers edge cases. A functional test tests the system from the user's perspective, verifying that features work correctly as a whole, often involving multiple components and external dependencies.
129
What is PEP 8?
Reference answer
It is a Python Enhancement Proposal, guidelines that determine Python code formats for better readability.
130
What does the Python not in operator do?
Reference answer
The Python not in operator evaluates to true if it does not find a variable in the specified sequence and false if it does not. # The following will return true 4 not in [1,2,3]
131
What are Python iterators?
Reference answer
Python iterators are objects that allow traversal through a sequence of elements, such as in loops. They implement the __iter__() and __next__() methods, and are used with for loops or manually via the iter() and next() functions.
132
Can you share a specific example where adhering to coding standards and best practices in Python resulted in a more maintainable and bug-free codebase?
Reference answer
Certainly. In a project, strict adherence to PEP 8 and consistent naming conventions made it easier for team members to understand and modify each other's code. This reduced the likelihood of introducing bugs during maintenance.
133
What is the correct syntax to output the type of a variable or object in Python?
Reference answer
print(type(x))
134
How do you traverse a binary tree level by level?
Reference answer
Use a queue for breadth-first traversal. Example: from collections import deque class Node: def __init__(self, val): self.val = val self.left = None self.right = None def level_order(root): if not root: return [] result = [] queue = deque([root]) while queue: level = [] for _ in range(len(queue)): node = queue.popleft() level.append(node.val) if node.left: queue.append(node.left) if node.right: queue.append(node.right) result.append(level) return result # Example usage: # root = Node(1) # root.left = Node(2) # root.right = Node(3) # root.left.left = Node(4) # root.left.right = Node(5) # print(level_order(root)) # Output: [[1], [2, 3], [4, 5]]
135
What are the built-in data types for numbers in Python, and how are they different?
Reference answer
Python has three built-in numeric types: integers (`int`), floating-point numbers (`float`), and complex numbers (`complex`). Integers are whole numbers, floats have decimal points, and complex numbers have a real and imaginary part.
136
What are modules in Python?
Reference answer
This is a file that includes a set of various functions and statements that can be added to an application. They are basically of two types: - Built-in Modules - User-defined Modules
137
How does Django handle sessions?
Reference answer
Django provides a session that lets you store and retrieve data on a per-site-visitor basis. Django abstracts the process of sending and receiving cookies, by placing a session ID cookie on the client side, and storing all the related data on the server side. So the data itself is not stored client side. This is nice from a security perspective.
138
Write a Python function and explain what's going on.
Reference answer
def Examplefunc(str): #function that outputs the str parameter print "The value is", str #no return statement needed in this function def Multiply(x,y): #function that computes the product of x and y return x*y #returning the product of x and y #Calling the functions Examplefunc(9) #9 passed as the parameter) answer = Multiply(4,2) #4 and 2 passed as the parameters print "The product of x and y is:",answer Output: The value is 9 The product of x and y is: 8 Explanation The function Examplefunc above takes a variable str as parameter and then prints this value. Since it only prints the value there is no need for a return command. The function Multiply takes two parameters x and y as parameters. It then computes the product and uses the return statement to return back the answer.
139
How can you find the IP address of a website in Python?
Reference answer
we can use the gethostbyname function from the socket module to look up the IP address of the given domain name.
140
What is the difference between the try and else blocks in a try statement in Python?
Reference answer
The try block in a try statement in Python contains the code that may raise an exception, whereas the else block contains the code that is executed if no exception is raised in the try block. The else block is typically used to perform additional operations that depend on the success of the try block.
141
What are lists and tuples in Python?
Reference answer
These are sequence data types used in a collection of objects. Both have different data types: lists are represented with square brackets and tuples are represented with parentheses. Example of list: [1,2,3,4,5,6,7] Example of tuples: (13, 90, 11)
142
Write a python code to illustrate classes and object.
Reference answer
class assassin: def __init__(self, name, age): self.name = name self.age = age a1 = assassin("John Wick", 28) print(a1.name) print(a1.age)
143
What is the difference between shallow copy and deep copy in Python?
Reference answer
Shallow copy is used when a new instance type gets created and it keeps the values that are copied in the new instance. Shallow copy is used to copy the reference pointers just like it copies the values. These references point to the original objects and the changes made in any member of the class will also affect the original copy of it. Shallow copy allows faster execution of the program and it depends on the size of the data that is used. Deep copy is used to store the values that are already copied. Deep copy doesn't copy the reference pointers to the objects. It makes the reference to an object and the new object that is pointed by some other object gets stored. The changes made in the original copy won't affect any other copy that uses the object. Deep copy makes execution of the program slower due to making certain copies for each object that is been called.
144
What is the purpose of the PYTHONCASEOK variable?
Reference answer
This is a variable specifically for running Python on the Windows operating system. It tells the Python interpreter to use case-insensitive match when trying to find imported libraries.
145
What are the new features added in Python 3.9.0.0 version?
Reference answer
The new features in Python 3.9.0.0 version are-
146
What is an Interpreted language?
Reference answer
An Interpreted language executes its statements line by line. Languages such as Python, Javascript, R, PHP, and Ruby are prime examples of Interpreted languages. Programs written in an interpreted language runs directly from the source code, with no intermediary compilation step.
147
What is init?
Reference answer
__init__ is a method or constructor in Python. This method is automatically called to allocate memory when a new object/ instance of a class is created. All classes have the __init__ method.
148
Does Python support multiple inheritance?
Reference answer
Multiple inheritance means that a class can be derived from more than one parent classes. Python does support multiple inheritance, unlike Java.
149
Describe a situation where you had to integrate Python with a non-Python system or service, such as a messaging queue or a RESTful API.
Reference answer
In a microservices architecture, I integrated Python services with RabbitMQ for asynchronous communication, using the pika library for message handling.
150
What are Pickling and Unpickling?
Reference answer
- Pickling: The pickle module converts any Python object into a byte stream (not a string representation). This byte stream can then be stored in a file, sent over a network or saved for later use. The function used for pickling is pickle.dump(). - Unpickling: The process of retrieving the original Python object from the byte stream (saved during pickling) is called unpickling. The function used for unpickling is pickle.load().
151
What is init method in python?
Reference answer
The init method works similarly to the constructors in Java. The method is run as soon as an object is instantiated. It is useful for initializing any attributes or default behaviour of the object at the time of instantiation. For example: class InterviewbitEmployee: # init method / constructor def __init__(self, emp_name): self.emp_name = emp_name # introduce method def introduce(self): print('Hello, I am ', self.emp_name) emp = InterviewbitEmployee('Mr Employee') # __init__ method is called here and initializes the object name with "Mr Employee" emp.introduce()
152
How do you handle async/await in Python for AI applications?
Reference answer
Asynchronous programming is essential for AI applications that make multiple API calls or handle concurrent requests. Python's asyncio module enables non-blocking I/O operations. Example: Concurrent LLM API calls: import asyncio from openai import AsyncOpenAI client = AsyncOpenAI() async def get_completion(prompt: str) -> str: response = await client.chat.completions.create( model="gpt-4", messages=[{"role": "user", "content": prompt}] ) return response.choices[0].message.content async def process_multiple_prompts(prompts: list[str]) -> list[str]: tasks = [get_completion(prompt) for prompt in prompts] return await asyncio.gather(*tasks) # Run concurrent requests prompts = ["Explain Python lists", "Explain Python dicts", "Explain Python sets"] results = asyncio.run(process_multiple_prompts(prompts)) for result in results: print(result)
153
How do you differentiate between .py and .pc files in Python?
Reference answer
A file in Python with extension ".py" are source files while with extension ".pyc" are compiled bytecode files generated by the compiler.
154
How will you check if a class is a child of another class?
Reference answer
This is done by using a method called issubclass() provided by python. The method tells us if any class is a child of another class by returning true or false accordingly. For example: class Parent(object): pass class Child(Parent): pass # Driver Code print(issubclass(Child, Parent)) #True print(issubclass(Parent, Child)) #False - We can check if an object is an instance of a class by making use of isinstance() method: obj1 = Child() obj2 = Parent() print(isinstance(obj2, Child)) #False print(isinstance(obj2, Parent)) #True
155
Explain the concept of conditional statements in Python.
Reference answer
- if, else, and elif statements control program flow based on conditions. - Example: if condition: # code block elif another_condition: # code block else: # code block
156
What do you understand by reindexing in pandas?
Reference answer
Reindexing is the process of conforming a dataframe to a new index with optional filling logic. If the values are missing in the previous index, then NaN/NA is placed in the location. A new object is returned unless a new index is produced that is equivalent to the current one. The copy value is set to False. This is also used for changing the index of rows and columns in the dataframe.
157
What is defaultdict in Python?
Reference answer
The Python dictionary, dict , contains words and meanings as well as key-value pairs of any data type. The defaultdict is another subdivision of the built-in dict class. How is defaultdict different? The defaultdict is a subdivision of the dict class. Its importance lies in the fact that it allows each new key to be given a default value based on the type of dictionary being created. A defaultdict can be created by giving its declaration, an argument that can have three values; list, set or int. According to the specified data type, the dictionary is created and when any key, that does not exist in the defaultdict is added or accessed, it is assigned a default value as opposed to giving a KeyError . Example The first code snippet below shows a simple dictionary and how when a key that does not exist in the dict is accessed, it gives an error. dict_demo = dict() print(dict_demo[3]) Now let's introduce a defaultdict and see what happens. from collections import defaultdict defaultdict_demo = defaultdict(int) print(defaultdict_demo[3]) Output: 0 In this case, we have passed int as the datatype to the defaultdict . Hence, any key that does not already exist in defaultdict_demo will be assigned a value of 0, unless a value is defined for it. Note: You can also have set orlist as the parameters
158
What is Python's role in future technologies?
Reference answer
Python has cemented its place as an integral part of future technologies due to its simplicity, versatility, and the vast ecosystem of libraries and frameworks it offers. As we look towards advancements in areas like artificial intelligence (AI), machine learning (ML), data analysis, and the Internet of Things (IoT), Python's role becomes increasingly significant. - Artificial Intelligence and Machine Learning: Python's syntax is clear and concise, which makes it an ideal language for complex AI and ML algorithms. Its libraries such as TensorFlow, PyTorch, and Keras facilitate the development of cutting-edge solutions by simplifying the implementation process. - Data Analysis: With the exponential growth of data, Python's powerful libraries like Pandas, NumPy, and Matplotlib are pivotal for data processing, manipulation, and visualization. These tools enable data scientists to derive meaningful insights from vast datasets. - Internet of Things (IoT): In the IoT space, Python's readability and compact code base are assets for developing applications that run on devices with limited computing power. Libraries like MicroPython extend Python's reach to even microcontrollers, making it a popular choice for IoT development. - Web Development: Python's web frameworks, such as Django and Flask, are renowned for their scalability and security, making them a go-to choice for building robust web applications. These frameworks will continue to be relevant as web technologies evolve. - Cybersecurity: As security becomes more crucial, Python's ability to script and automate tasks is invaluable for penetration testing and vulnerability analysis. Its libraries can be used to develop tools that help in securing networks and systems.
159
What are lambdas (anonymous functions) in Python?
Reference answer
Lambdas are small, anonymous functions defined using the lambda keyword. They are often used for short, simple operations.
160
How do you transpose a matrix in NumPy?
Reference answer
You can transpose a matrix in NumPy using the numpy.transpose() function or the .T attribute of a NumPy array. For example, numpy.transpose(matrix) or matrix.T.
161
Write a Python code to check if a number is a perfect square
Reference answer
def is_perfect_square(x): return int(x ** 0.5) ** 2 == x print(is_perfect_square(16)) # True print(is_perfect_square(14)) # False
162
This code is supposed to use a generator function to yield all prime numbers up to a given limit. Fix the code. def primes(limit): i = 2 while i < limit: for j in range(2, i): if i % j == 0: break else: yield i i += 1 print(list(primes(20)))
Reference answer
The code is correct and will generate a list of prime numbers up to 20.
163
Write a Python function to find the maximum difference between two elements in a list.
Reference answer
Solution: def max_difference(nums): if len(nums) < 2: return None # If the list has less than two elements, return None min_element = float('inf') # Initialize min_element to positive infinity max_difference = float('-inf') # Initialize max_difference to negative infinity for num in nums: min_element = min(min_element, num) max_difference = max(max_difference, num - min_element) return max_difference # Example usage numbers = [7, 1, 5, 3, 6, 4] result = max_difference(numbers) if result is not None: print("Maximum difference between two elements in the list:", result) else: print("The list has less than two elements.") Output: Maximum difference between two elements in the list: 5
164
What is the difference between isinstance() and type()?
Reference answer
- isinstance() checks if an object is an instance of a class or its subclass. - type() checks the exact type of an object. Example: print(isinstance(5, int)) # True print(type(5) is int) # True
165
How do you delete a file in Python?
Reference answer
Import OR module and use os.remove().
166
What are the differences between pickling and unpickling?
Reference answer
Pickling is the conversion of python objects to binary form. Whereas, unpickling is the conversion of binary form data to python objects. The pickled objects are used for storing in disks or external memory locations. Unpickled objects are used for getting the data back as python objects upon which processing can be done in python. Python provides a pickle module for achieving this. Pickling uses the pickle.dump() method to dump python objects into disks. Unpickling uses the pickle.load() method to get back the data as python objects.
167
How would you get all the keys in a Python dictionary?
Reference answer
You would use the dictionary keys function. dict={'first':'Bob', 'last':'Smith'} all_keys=dict.keys()
168
What is a lambda function in Python, and how is it different from a regular function?
Reference answer
A lambda function is an anonymous, small, and inline function defined using the `lambda` keyword. They are typically used for short, simple operations and do not have a name.
169
How can you combine dataframes in Python?
Reference answer
The dataframes in Python can be combined in the following ways- The concat() function is used to concatenate two dataframes. Its syntax is- pd.concat([dataframe1, dataframe2]). Dataframes are joined together on a common column called a key. When we combine all the rows in dataframe it is a union and the join used is outer join. While, when we combine the common rows or intersection, the join used is the inner join. Its syntax is- pd.concat([dataframe1, dataframe2], axis='axis', join='type_of_join)
170
Create a REST API endpoint in the Flask application that responds to GET requests at /api/data. It should return a JSON object with a key message and value "Flask API response".
Reference answer
from flask import Flask, jsonify app = Flask(__name__) @app.route('/api/data', methods=['GET']) def get_data(): return jsonify({'message': 'Flask API response'}) if __name__ == '__main__': app.run(debug=True) Explanation of solution: The Flask route /api/data is defined to handle GET requests. The view function get_data returns a JSON response using jsonify, a Flask utility to convert Python dictionaries to JSON. The response contains a message. This setup demonstrates how to create a simple RESTful endpoint in Flask.
171
What is pass in Python?
Reference answer
Pass is a placeholder for the future code in Python. When the pass statement is executed, no operation takes place. It basically depicts a blank space, however, in places, like loops, class definitions, conditional statements such as: if statements, or even in function definitions, where empty code is not permitted, a pass can be used to prevent an error. The pass statement is not ignored by the Python interpreter, as it returns a null value, therefore it is different from a comment, which is ignored by the Python interpreter.
172
Convert max heap to min heap
Reference answer
Here we'll Min Heapify all Parent Nodes. def minHeapify(heap, index): left = index * 2 + 1 right = (index * 2) + 2 smallest = index # check if left child exists and is less than smallest if len(heap) > left and heap[smallest] > heap[left]: smallest = left # check if right child exists and is less than smallest if len(heap) > right and heap[smallest] > heap[right]: smallest = right # check if current index is not the smallest if smallest != index: # swap current index value with smallest tmp = heap[smallest] heap[smallest] = heap[index] heap[index] = tmp # minHeapify the new node minHeapify(heap, smallest) return heap def convertMax(maxHeap): # iterate from middle to first element # middle to first indices contain all parent nodes for i in range((len(maxHeap))//2, -1, -1): # call minHeapify on all parent nodes maxHeap = minHeapify(maxHeap, i) return maxHeap maxHeap = [9, 4, 7, 1, -2, 6, 5] print(convertMax(maxHeap)) Output: [-2, 1, 5, 9, 4, 6, 7] Explanation Remember that we can consider the given maxHeap to be a regular list of elements and reorder it so that it represents a min heap accurately. We do exactly that in this solution. The convertMax() function restores the heap property on all the nodes from the lowest parent node by calling the minHeapify() function on each. Time Complexity The minHeapify() function is called for half of the nodes in the heap. The minHeapify() function takes O(log(n)) time and its called on nodes so this solution takes O(nlog(n)) time.
173
Why are functions considered first class objects in Python?
Reference answer
Functions are considered first class objects in Python because they can be assigned to variables, passed as arguments to other functions, returned from functions, and stored in data structures. This allows for higher-order functions and functional programming techniques.
174
How do you handle multithreading for concurrent API requests in Python?
Reference answer
Use the concurrent.futures.ThreadPoolExecutor to efficiently manage multiple threads for I/O-bound tasks like API calls. Example: import requests from concurrent.futures import ThreadPoolExecutor urls = ['https://api.example.com/a', 'https://api.example.com/b'] def fetch(url): return requests.get(url).json() with ThreadPoolExecutor(max_workers=5) as executor: results = list(executor.map(fetch, urls)) print(results)
175
What are unit tests in Python?
Reference answer
Unit tests in Python are automated tests that verify the correctness of individual units of code, such as functions or methods. They are typically written using frameworks like unittest or pytest to ensure code reliability.
176
23. Can you explain the uses of generators in Python?
Reference answer
Python Generator functions allow you to declare a function that behaves like an iterator, allowing programmers to make an iterator in a fast, easy, and clean way. Python generators allow for the creation of iterators using simple functions rather than implementing complex classes. A generator produces items one at a time using the `yield` keyword, instead of returning a whole sequence. This leads to efficient memory usage because items are generated on-the-fly and aren't stored in memory all at once. Generators are useful when working with large datasets or infinite sequences. Read large files line by line with generators, if loading the entire file in memory isn't feasible. They facilitate the creation of custom, complex iteration patterns. Generators offer both memory efficiency and flexibility in handling data streams in Python applications.
177
What is the output of the following code? print(var) if var='Hello Everyone!'
Reference answer
The output would be: Hello Everyone!
178
What are Python modules?
Reference answer
A Python module is a Python file containing a set of functions and variables to be used in an application. The variables can be of any type (arrays, dictionaries, objects, etc.) Modules can be either: Built in User-defined Benefits of modules in Python There are a couple of key benefits of creating and using a module in Python: - Structured Code - Code is logically organized by being grouped into one Python file which makes development easier and less error-prone. - Code is easier to understand and use. - Reusability - Functionality defined in a single module can be easily reused by other parts of the application. This eliminates the need to recreate duplicate code.
179
What advantages do NumPy arrays offer over (nested) Python lists?
Reference answer
- Python's lists are efficient general-purpose containers. They support (fairly) efficient insertion, deletion, appending, and concatenation, and Python's list comprehensions make them easy to construct and manipulate. - They have certain limitations: they don't support “vectorized” operations like elementwise addition and multiplication, and the fact that they can contain objects of differing types mean that Python must store type information for every element, and must execute type dispatching code when operating on each element. - NumPy is not just more efficient; it is also more convenient. You get a lot of vector and matrix operations for free, which sometimes allow one to avoid unnecessary work. And they are also efficiently implemented. - NumPy array is faster and You get a lot built in with NumPy, FFTs, convolutions, fast searching, basic statistics, linear algebra, histograms, etc.
180
How do you perform API interactions in Python?
Reference answer
The requests library lets you send HTTP requests and responses. Example: import requests # Make a GET request response = requests.get('https://api.example.com/data') # Check if the request was successful if response.status_code == 200: data = response.json() print(data) else: print(f"Request failed with status code {response.status_code}")
181
How can you work with binary data in Python, and what are the benefits of using the struct module?
Reference answer
You can work with binary data using the `struct` module``, which allows you to pack and unpack binary data into``/``from Python objects.
182
How does Python handle memory management? Explain the role of reference counting and garbage collection?
Reference answer
Python uses a combination of reference counting and garbage collection for memory management. Reference counting keeps track of the number of references to an object, and when the reference count becomes zero, the memory for that object is deallocated. Garbage collection is a process that runs periodically to identify and clean up objects that are no longer reachable, even if they have circular references.
183
What is the difference between a function and a method in Python?
Reference answer
A function is a standalone block of code that performs a specific task, while a method is a function that is associated with an object and can access and modify its data.
184
What is self?
Reference answer
Self is a first argument of a method. A method defined as do_something(self, a, b, c) should be called as object.do_something(a, b, c) for some instance object of the class in which the definition occurs; the called method will think it is called as do_something(self, a, b, c).
185
100. What is mocking in testing, and how can it be implemented in Python?
Reference answer
Mocking in testing refers to the practice of simulating specific behaviors, functionalities, or attributes. This is done to isolate a piece of code and test it without relying on external systems or real-world scenarios. Mocking allows a developer to ensure a function or module behaves as expected, even if dependencies change or are unpredictable. The `unittest` library provides a `Mock` class to create mock objects. You replace parts of your system under test with mock objects and make assertions about how they have been used by using this class. For example, You'd use a mock to mimic the API's response, if testing a function that makes an API call. This way, you test the function without making an actual API call.
186
You're dealing with a large CSV file containing messy data. How would you clean and validate it before further analysis?
Reference answer
- Answer: I'd use regular expressions and Pandas utilities to handle missing values, inconsistencies, and invalid formats. Data validation libraries like Pandas-Schema or PyPI's 'datachecker' could also be helpful.
187
What is package management in Python?
Reference answer
Package management in Python refers to installing, upgrading, and removing Python libraries, usually using pip.
188
Multiple Choice Question: What is the output of the following code? x = [0,1,[2]] x[2][0] = 3 print(x) a) [0, 1, 3] b) [0, 1, 2] c) [0, 1, [3]] d) invalid code
Reference answer
Answer: c) 25 The index -1 corresponds to the last index in the list.
189
What is a Python generator, and how is it different from a list?
Reference answer
Generators are iterators that produce values one at a time using the yield keyword. Unlike lists, generators do not store all values in memory, making them memory-efficient. Example: def gen_numbers(): for i in range(5): yield i gen = gen_numbers() print(next(gen)) # 0 print(next(gen)) # 1
190
What is inheritance? Name the main types of Python inheritance.
Reference answer
Inheritance is a way for a class to pass its members (e.g. methods or attributes) to a new class. In this case, a class that contains the original data is called a super-class. The inheriting class is called a child or derived class. There are four inheritance types in Python: - Single inheritance – a child class inherits the data passed down by one super-class. - Multiple inheritance – a child class inherits the members of several super-classes. - Multi-level inheritance – a derived class d1 inherits the members of a super-class b1; a child class d2 inherits the data from a base class b2. - Hierarchical inheritance – a high number of child classes can inherit the members of one superclass.
191
What are the differences between Wheels and Eggs?
Reference answer
Both Wheel and Egg are packaging formats that don't require the compilation of install artifacts. Out of the two, Wheel is the newer one and is considered a standard recommendation for Python developers. Here's the breakdown of the differences between Wheels and Eggs: | Wheel | Egg | | Has an official PEP | Does not have an official PEP | | Packaging (distribution) format only | Distribution and installation format | | Wheel specifications are versioned | Egg is not versioned | | PEP-376 compliance | Uses egg.info | | Robust naming conventions | Limited naming convention |
192
What is a string in Python?
Reference answer
A string is a sequence of characters enclosed in single (' ') or double (" ") quotes.
193
Write a Python program to calculate the area of a rectangle
Reference answer
def area_of_rectangle(length, width): return length * width print(area_of_rectangle(5, 3)) # 15
194
Do arguments in Python get passed by reference or by value?
Reference answer
Arguments in Python are passed by assignment, which is sometimes called 'call by object reference' or 'call by sharing.' The parameter receives a reference to the object, but the reference is passed by value. Mutable objects can be modified inside a function, but reassigning the parameter does not affect the original variable.
195
LRU Cache: How would you design an LRU cache with O(1) get and put?
Reference answer
You use a dictionary for fast lookup and a doubly linked list (or OrderedDict) to track recent usage, when you access an item you move it to the end, when cache is full you remove the least recently used item, this gives O(1) time for both get and put. from collections import OrderedDict class LRUCache: def __init__(self, cap): self.cap = cap self.cache = OrderedDict() def get(self, key): if key not in self.cache: return -1 self.cache.move_to_end(key) return self.cache[key] def put(self, key, val): if key in self.cache: self.cache.move_to_end(key) self.cache[key] = val if len(self.cache) > self.cap: self.cache.popitem(last=False)
196
What is the difference between a list and a tuple?
Reference answer
| List | Tuple | |---|---| | A list consists of mutable objects. (Objects which can be changed after creation) | A tuple consists of immutable objects. (Objects which cannot change after creation) | | List has a large memory. | Tuple has a small memory. | | List is stored in two blocks of memory (One is fixed sized and the other is variable sized for storing data) | Tuple is stored in a single block of memory. | | Creating a list is slower because two memory blocks need to be accessed. | Creating a tuple is faster than creating a list. | | An element in a list can be removed or replaced. | An element in a tuple cannot be removed or replaced. | | A list has data stored in [] brackets. For example, [1,2,3] | A tuple has data stored in () brackets. For example, (1,2,3) | When to use each: A tuple should be used whenever the user is aware of what is inserted in the tuple. Suppose that a college stores the information of its students in a data structure; in order for this information to remain immutable it should be stored in a tuple. Since lists provide users with easier accessibility, they should be used whenever similar types of objects need to be stored. For instance, if a grocery needs to store all the dairy products in one field, it should use a list.
197
What are Python's magic methods?
Reference answer
Magic methods are special methods surrounded by double underscores. Examples: - __init__: Constructor for initializing objects. - __str__: Provides a string representation of an object. - __add__: Overloads the + operator. Example: class Point: def __init__(self, x, y): self.x = x self.y = y def __str__(self): return f"Point({self.x}, {self.y})" point = Point(1, 2) print(point) # Point(1, 2)
198
Can you find a Pythagorean triplet in an array?
Reference answer
Write a function that returns True if there is a Pythagorean triplet that satisfies a2+ b2 = c2. Example: | Input | Output | | [3, 1, 4, 6, 5] | True | | [10, 4, 6, 12, 5] | False | Solution: - Square all the elements in the array. - Sort the array in increasing order. - Run two loops. The outer loop starts from the last index of the array to 1, and the inner loop starts from (outer_loop_index - 1) to the start. - Create set() to store the elements between outer loop index and inner loop index. - Check if there is a number present in the set which is equal to (array[outerLoopIndex] – array[innerLoopIndex]). If yes, return True, else False. def checkTriplet(array): n = len(array) for i in range(n): array[i] = array[i]**2 array.sort() for i in range(n - 1, 1, -1): s = set() for j in range(i - 1, -1, -1): if (array[i] - array[j]) in s: return True s.add(array[j]) return False arr = [3, 2, 4, 6, 5] checkTriplet(arr) # True
199
What is the Python GIL and how does it affect multithreading?
Reference answer
GIL means Global Interpreter Lock. It allows only one thread to run Python code at a time. So, CPU-heavy programs don't get faster with threads.Threads are still useful for I/O work like file, network, or API calls.GIL keeps memory safe but limits performance. That's why Python uses multiprocessing for heavy tasks. # Threads help more in I/O, not CPU-heavy tasks import threading def task(): print("Running task") t1 = threading.Thread(target=task) t2 = threading.Thread(target=task) t1.start() t2.start()
200
How would you use a dictionary to count the frequency of words in a large text file?
Reference answer
You can iterate over each word in the file, using a dictionary where keys are words and values are counts. For each word, check if it exists in the dictionary; if yes, increment its count; if no, add it with count 1. To handle large files, process line by line to avoid memory issues.