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

Mock Interview Questions for Python Developers | 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
What is PEP 8 and why is it important?
Reference answer
PEP 8 is the official style guide for Python. Therefore, it promotes code readability and consistency for any Python project.
2
What is the purpose of the .merge() method in Pandas, and when is it used?
Reference answer
The `.merge()` method is used to combine two DataFrames into a single DataFrame based on common columns or indices. It is similar to SQL JOIN operations.
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 are the advantages of NumPy over Python lists?
Reference answer
NumPy uses less storage, is faster, and has many vector and matrix operations that eliminate the need for oftentimes unnecessary work. Its slicing and broadcasting functionality are more powerful than those of regular Python lists.
4
Write a program in Python to check if a number is prime.
Reference answer
a = int(input("Enter a number = ")) if a == 1: print("Not a prime number.") else: for x in range(2, a): if (a % x) == 0: print("Not a prime number.") break else: print("Prime Number.")
5
What is a Python namespace?
Reference answer
Namespaces in Python ensure that Python variables, functions, and other names don't clash.
6
Write a Python code to convert a list of temperatures from Celsius to Fahrenheit
Reference answer
def celsius_to_fahrenheit(temps): return [(temp * 9/5) + 32 for temp in temps] print(celsius_to_fahrenheit([0, 20, 37])) # [32.0, 68.0, 98.6]
7
What are metaclasses in Python, and how are they used?
Reference answer
Metaclasses are classes of classes that define how classes behave. They are used to create APIs, enforce coding standards, or modify class creation.
8
What is the purpose of lambda functions in Python, and how are they different from regular functions?
Reference answer
Lambda functions are used to create small, anonymous functions that can be used in place of regular functions. They are different from regular functions in that they do not have a name and can only contain a single expression.
9
What is pickling and unpickling in Python?
Reference answer
Pickling is the process of converting a Python object into a byte stream, and unpickling is the reverse operation. The pickle module provides this functionality.
10
Is Indentation Necessary in Python?
Reference answer
The indentation may be just for easier reading in other languages but it is essential in Python. It indicates a block of code, and without it, you will face the error message and the code will not be compiled.
11
How to identify items in Series A but not in Series B?
Reference answer
The below program will help you in identifying items in series A but no in series B: import pandas as pd # Creating 2 pandas Series ps1 = pd.Series([2, 4, 8, 20, 10, 47, 99]) ps2 = pd.Series([1, 3, 6, 4, 10, 99, 50]) print("Series 1:") print(ps1) print("nSeries 2:") print(ps2) # Using Bitwise NOT operator along # with pandas.isin() print("nItems of Series 1 not present in Series 2:") res = ps1[~ps1.isin(ps2)] print(res)
12
How can you remove values from an array in Python?
Reference answer
They can be removed using the remove() or pop() function.
13
What are Python modules? Name some commonly used built-in modules in Python.
Reference answer
Python modules are files containing Python code. This code can either be functions classes or variables. A Python module is a .py file containing executable code. Some of the commonly used built-in modules are:
14
Describe the use of the pass statement.
Reference answer
pass is a null statement in Python. It does nothing when executed and is used as a placeholder.
15
What are data types in Python?
Reference answer
Data types define the type of data a variable can hold. Common data types include int, float, str, bool, and more.
16
Is indentation necessary in Python?
Reference answer
Indentation is necessary for Python. It specifies a block of code. All code within loops, classes, functions, etc is specified within an indented block. It is usually done using four space characters. If your code is not indented necessarily, it will not execute accurately and will throw errors as well.
17
Explain the concept of list comprehension in Python.
Reference answer
List comprehension is a concise way to create lists in Python. It allows you to generate a list by specifying the elements you want to include and the conditions they must satisfy. squares = [x**2 for x in range(5)] # Result: [0, 1, 4, 9, 16]
18
What is PEP 8 ?
Reference answer
PEP 8 is a guide that helps in writing clean, consistent, and maintainable Python code that is easy to read and understand. It stands for Python Enhancement Proposal, it specifically provides guidelines and recommendations on how to format and structure Python code to enhance readability and reliability of the code. Some key points of PEP 8 include: - Indentation: Use 4 spaces for indentation to improve code readability. - Line Length: Limit lines to a maximum of 79 characters to ensure readability, although it can be extended up to 120 characters in certain cases. - Naming Conventions - Function and Variable Names - Imports: Import modules on separate lines and follow a specific ordering convention (standard library modules, third-party modules, local modules). - It also provides numerous other guidelines covering various aspects of coding style, including whitespace, blank lines, operator spacing, and more.
19
What is the use of dictionaries in python?
Reference answer
Dictionary in python are used for mapping of unique keys to values.
20
Name some popular Python web frameworks.
Reference answer
Those are Django, Flask, and Pyramid. Flask aims at small applications while Django and Pyramid were created for larger projects. Pyramid is very flexible, developers can choose all the tools they want from database to templating style. Django has ORM and many other tools out of the box.
21
What are Python decorators?
Reference answer
Decorators allow developers to modify or extend the behavior of callable objects (like functions or methods) without permanently modifying the callable itself.
22
Can you explain the concept of versioning in RESTful APIs and describe how you would implement it to ensure backward compatibility?
Reference answer
API versioning is important for maintaining compatibility. We would typically include the version in the URL, such as /api/v1/resource, and use URL routing or middleware to handle requests to the appropriate version.
23
How are global and local variables defined in Python?
Reference answer
In general, variables defined outside of functions are global. Variables defined inside a function can also be made global by using the command global x, for example, to create a global variable called x.
24
Explain the use of version control systems in your projects.
Reference answer
Version control systems like Git help track changes, collaborate with team members, manage branches, and handle code merges and conflicts.
25
What is encapsulation in Python?
Reference answer
Encapsulation means binding the code and the data together. A Python class in an example of encapsulation.
26
What is the purpose of the .loc[] method in Pandas?
Reference answer
The `.loc[]` method is used for label-based indexing. It allows you to select rows and columns by labels, rather than by their integer position.
27
How do you handle and avoid infinite loops in Python programs?
Reference answer
Infinite loops occur when a loop's condition never becomes False, causing it to run indefinitely. To avoid infinite loops, you need to ensure that the loop's condition eventually evaluates to False. Common techniques to handle infinite loops include using a loop control variable, using a break statement within the loop, or using conditional checks to exit the loop based on certain conditions. Additionally, using a timeout mechanism or Keyboard Interrupt exception handling can be used to interrupt infinite loops during development and testing.
28
What is docstring in Python?
Reference answer
Docstring is a string literal used to document modules, classes, functions, and methods. It serves as a documentation tool to describe the purpose, behavior, parameters, return values, and other important details of the code. A docstring is enclosed in triple quotes (single or double) and is typically placed as the first line after the definition of a module, class, function, or method. It can span multiple lines and supports both single-line and multi-line docstrings. def hello(name): """ This function says hello to the person with the given name. Parameters: name (str): The name of the person to be greeted. Returns: str: A greeting message. """ return "Hello, " + name + " !!!!!" print(hello("Isabelle"))
29
45. How to implement breadth-first search in Python?
Reference answer
Breadth-first search (BFS) is implemented in Python using a queue data structure. Start by initializing a queue and adding the starting node to it. Make sure the queue is not empty, remove the first node and process it and add all its unvisited neighbors to the queue. Mark nodes as visited once they're processed, ensuring they aren't revisited. The process continues until the queue is empty or the desired node is found. You can use an adjacency list or matrix, to represent the graph. Python's built-in list or the `collections.deque` can be used for the queue operations. Check if a node has been visited before adding it to the queue, preventing infinite loops in cyclic graphs.
30
Given a string S, find the indices of the start and end of string k in S.
Reference answer
Sample Input: aaadaa aa Sample Output: (0, 1) (1, 2) (4, 5) Task: Find the indices of the start and end of string k in S. If no match is found, print (-1, -1).
31
Define monkey-patching.
Reference answer
Python allows software developers to change the behavior of a module at runtime. To make these dynamic edits, programmers use monkey-patching.
32
How do you merge Pandas dataframes using multiple keys?
Reference answer
Pandas dataframes can be merged using multiple keys by passing a list of columns to the on parameter of the merge() function. This allows you to merge dataframes based on more than one common column.
33
How can you alter functions in python syntax?
Reference answer
By using the decorators we can alter the functions easily.
34
What is the difference between lists and tuples in Python?
Reference answer
Lists are mutable sequences that allow elements to be added, removed, or modified after creation. Tuples are immutable; their structure and references cannot be changed once instantiated. Tuples have a lower memory footprint and are faster to create and iterate over because they are allocated exact memory, while lists over-allocate for O(1) amortized append() operations. Tuples (containing only hashable elements) are hashable and can be used as dictionary keys or set elements; lists are unhashable. Lists are ideal for collections requiring frequent updates or resizing, while tuples are preferred for fixed data structures, protecting data from accidental modification, and serving as constant keys in mapping types.
35
What is the difference between a syntax error and a runtime error in Python?
Reference answer
A syntax error is a type of error that occurs when Python cannot parse the code due to a violation of the language grammar rules, such as a missing parenthesis or a typo in a keyword. A runtime error, on the other hand, occurs when Python is able to parse the code but encounters an error while running it, such as a division by zero or an undefined variable.
36
What is break, continue and pass in Python?
Reference answer
| Break | The break statement terminates the loop immediately and the control flows to the statement after the body of the loop. | | Continue | The continue statement terminates the current iteration of the statement, skips the rest of the code in the current iteration and the control flows to the next iteration of the loop. | | Pass | As explained above, the pass keyword in Python is generally used to fill up empty blocks and is similar to an empty statement represented by a semi-colon in languages such as Java, C++, Javascript, etc. | pat = [1, 3, 2, 1, 2, 3, 1, 0, 1, 3] for p in pat: pass if (p == 0): current = p break elif (p % 2 == 0): continue print(p) # output => 1 3 1 3 1 print(current) # output => 0
37
What is the difference between Flask and Pyramid?
Reference answer
Flask is a “microframework” primarily build for a small application with simpler requirements. In flask, you have to use external libraries. Flask is ready to use. Pyramid is built for larger applications. It provides flexibility and lets the developer use the right tools for their project. The developer can choose the database, URL structure, templating style and more. Pyramid is heavy configurable. Django can also be used for larger applications just like Pyramid. It includes an ORM.
38
What is the difference between a list and a tuple in Python?
Reference answer
Both lists and tuples can store an ordered array of objects, however, a tuple is immutable. This means that once a tuple is created with objects in it, the objects can not be swapped out (mutating). A list still allows for objects to be reassigned within the list.
39
What is Dictionary Comprehension? Give an Example
Reference answer
Dictionary Comprehension is a concise way to create dictionaries from existing iterables. It allows you to generate key-value pairs in a single line of code, making the code more readable and efficient. keys = ['a', 'b', 'c', 'd', 'e'] values = [1, 2, 3, 4, 5] # Dictionary comprehension d = {k: v for k, v in zip(keys, values)} print(d) Output {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
40
Name the differences between a list and a tuple in Python.
Reference answer
Although both lists and tuples are data collections, there are fundamental differences between the two. Knowing them helps developers choose which collection type they want to use. | Lists | Tuples | | Mutability: items on the list can be changed | Immutability: there's no way to edit a tuple | | Lower speed than that of tuples | Higher speed than that of lists | | Uses square brackets: mylist=[1, "Python", 1.5] | Uses round brackets: mytuple=(1, "Python", 1.5) |
41
How does Python handle memory management?
Reference answer
Python uses automatic memory management, employing techniques such as: - Reference Counting: Tracks the number of references to objects. - Garbage Collection: Frees up memory for objects no longer in use, using algorithms like generational garbage collection.
42
What is the difference between a generator and an iterator?
Reference answer
An iterator is any object that you can loop over using for, like a list or a tuple. It has two methods: __iter__() and __next__(). A generator is a special kind of iterator made using a function and the yield keyword. Generators don't store all values in memory at once; they give values one by one. This saves memory and is useful for large data or streams. So, every generator is an iterator, but not every iterator is a generator. # Iterator example nums = [1, 2, 3] it = iter(nums) print(next(it)) # 1 print(next(it)) # 2 # Generator example def count_up(n): for i in range(n): yield i gen = count_up(3) print(next(gen)) # 0 print(next(gen)) # 1
43
Implement merge sort in Python
Reference answer
Here is the code for merge sort in Python: def mergeSort(myList): if len(myList) > 1: mid = len(myList) // 2 left = myList[:mid] right = myList[mid:] # Recursive call on each half mergeSort(left) mergeSort(right) # Two iterators for traversing the two halves i = 0 j = 0 # Iterator for the main list k = 0 while i < len(left) and j < len(right): if left[i] < right[j]: # The value from the left half has been used myList[k] = left[i] # Move the iterator forward i += 1 else: myList[k] = right[j] j += 1 # Move to the next slot k += 1 # For all the remaining values while i < len(left): myList[k] = left[i] i += 1 k += 1 while j < len(right): myList[k]=right[j] j += 1 k += 1 myList = [54,26,93,17,77,31,44,55,20] mergeSort(myList) print(myList) Output: [17, 20, 26, 31, 44, 54, 55, 77, 93] Explanation This is the recursive approach for implementing merge sort. The steps needed to obtain the sorted array through this method can be found below: The list is divided into left andright in each recursive call until two adjacent elements are obtained.Now begins the sorting process. The i andj iterators traverse the two halves in each call. Thek iterator traverses the whole lists and makes changes along the way.If the value at i is smaller than the value atj ,left[i] is assigned to themyList[k] slot andi is incremented. If not, thenright[j] is chosen.This way, the values being assigned through k are all sorted.At the end of this loop, one of the halves may not have been traversed completely. Its values are simply assigned to the remaining slots in the list. Time complexity The algorithm works in O(n.logn). This is because the list is being split in log(n) calls and the merging process takes linear time in each call.
44
Demonstrate data visualization techniques in Pandas using matplotlib or seaborn.
Reference answer
- Create basic plots like histograms, bar charts, line charts, and boxplots.
45
What Do You Understand by PYTHONPATH?
Reference answer
PYTHONPATH is an environment variable that developers use to add (and maintain) additional directories without installing them in the global default location. It achieves this by creating additional folders to the sys.path directory list of program in Python where it can look for modules and packages.
46
What do you mean by local variables?
Reference answer
A variable which you define inside the function is known as local variable, you can not use local variable outside the function.
47
How Python is interpreted?
Reference answer
- Python as a language is not interpreted or compiled. Interpreted or compiled is the property of the implementation. Python is a bytecode(set of interpreter readable instructions) interpreted generally. - Source code is a file with .py extension. - Python compiles the source code to a set of instructions for a virtual machine. The Python interpreter is an implementation of that virtual machine. This intermediate format is called "bytecode". - .py source code is first compiled to give .pyc which is bytecode. This bytecode can be then interpreted by the official CPython or JIT(Just in Time compiler) compiled by PyPy.
48
How do you use assertions in Python for testing?
Reference answer
Use the assert statement to check conditions during development or tests. Example: def divide(a, b): assert b != 0, "Denominator cannot be zero" return a / b print(divide(10, 2)) # 5.0
49
What is a Large Language Model (LLM), and how would you use one in Python?
Reference answer
A Large Language Model (LLM) is a deep learning model trained on massive text datasets to understand and generate human-like text. Popular LLMs include GPT-5, Claude, Llama, and Gemini. In Python, you can interact with LLMs through APIs or run them locally. Example using OpenAI's API: from openai import OpenAI client = OpenAI(api_key="your-api-key") response = client.chat.completions.create( model="gpt-4", messages=[ {"role": "system", "content": "You are a helpful assistant."}, {"role": "user", "content": "Explain Python decorators in simple terms."} ] ) print(response.choices[0].message.content)
50
What is vectorization in NumPy, and why is it important?
Reference answer
Vectorization is the process of performing mathematical operations on arrays of data rather than using loops to perform these operations on each individual element of the array. Vectorization in NumPy is important because it allows for faster and more efficient computation of numerical operations, making it a crucial tool for scientific computing and data analysis.
51
Describe the concept of ABCs (Abstract Base Classes) in Python and when you would use them.
Reference answer
ABCs define abstract methods that must be implemented by subclasses. They're used to enforce interfaces and create extensible frameworks.
52
What is monkey-patching in Python?
Reference answer
Python developers are able to make dynamic edits, edits of the module during the runtime. Monkey-patching helps them do so.
53
How do you use environment variables securely in Python applications?
Reference answer
Keep sensitive information out of code by accessing environment variables via the OS module. Example: import os # Get the API key from environment variables api_key = os.environ.get('API_KEY') print(api_key) # Prints None if 'API_KEY' is not set
54
Write a function that takes a string and returns the length of the longest substring without repeating characters.
Reference answer
def longest_unique_substring(s): char_index = {} max_length = 0 start = 0 for i, char in enumerate(s): if char in char_index and char_index[char] >= start: start = char_index[char] + 1 char_index[char] = i max_length = max(max_length, i - start + 1) return max_length
55
How do you create a list of unique random numbers in Python?
Reference answer
You can create a list of unique random numbers by using the `random.sample()` function, specifying the range and the number of unique numbers you want.
56
What is a decorator in Python and how does it work?
Reference answer
A decorator is a design pattern and language feature that allows dynamically modifying or extending the behavior of functions or classes without changing their source code. Decorators are higher-order functions that take another function as an argument and return a new function. They leverage closures to 'wrap' the original function, allowing code execution both before and after the target function runs. Common use cases include authorization, logging/profiling, caching/memoization, validation, and rate limiting. The @decorator syntax is syntactic sugar for func = decorator(func). Modern Python development requires functools.wraps to preserve the original function's metadata (__name__, __doc__, type annotations). Decorator factories (additional nesting) allow passing arguments to decorators.
57
What is a generator in Python, and how is it different from a regular function?
Reference answer
A generator is a special type of iterable that yields values one at a time, allowing for efficient memory usage. Generators are created using functions with `yield` statements and save and resume state between calls.
58
How do you comment in Python?
Reference answer
Use the # symbol for single-line comments, like this: # This is a comment
59
What is pickling and unpickling?
Reference answer
Pickle module accepts any Python object and converts it into a string representation and dumps it into a file by using dump function, this process is called pickling. While the process of retrieving original Python objects from the stored string representation is called unpickling.
60
What is RAG (Retrieval-Augmented Generation), and why is it important?
Reference answer
RAG combines retrieval systems with generative AI to produce more accurate, grounded responses. Instead of relying solely on the LLM's training data, RAG retrieves relevant documents from a knowledge base and uses them as context for generation. Key components of a RAG system: - Document Store: A vector database (like Pinecone, Chroma, or FAISS) storing embedded documents - Retriever: Finds relevant documents based on query similarity - Generator: An LLM that produces responses using retrieved context Example RAG workflow: from langchain.vectorstores import Chroma from langchain.embeddings import OpenAIEmbeddings from langchain.chat_models import ChatOpenAI from langchain.chains import RetrievalQA # Create vector store from documents embeddings = OpenAIEmbeddings() vectorstore = Chroma.from_documents(documents, embeddings) # Create RAG chain llm = ChatOpenAI(model="gpt-4") qa_chain = RetrievalQA.from_chain_type( llm=llm, retriever=vectorstore.as_retriever() ) # Query the system result = qa_chain.invoke("What are Python best practices?") print(result)
61
Is Python a case-sensitive language?
Reference answer
Yes, it is a case-sensitive language.
62
What is the purpose of the finally block in a try statement in Python?
Reference answer
The finally block in a try statement in Python is executed regardless of whether an exception is raised or not. It is typically used to perform cleanup tasks, such as closing a file or releasing a resource.
63
How to import modules in python?
Reference answer
Modules can be imported using the import keyword. You can import modules in three ways- Example: import array #importing using the original module name import array as arr # importing using an alias name from array import * #imports everything present in the array module
64
42. How to write a Python script to merge two Python dictionaries?
Reference answer
To write a Python script to merge two Python dictionaries, use the `update()` method or the `**` unpacking operator. Using the `update()` method, the second dictionary's keys and values get added to the first dictionary. Keys value gets updated, If the key already exists in the first dictionary. For example, `dict1.update(dict2)` will merge `dict2` into `dict1`. With Python 3.5 and later, you can use the `**` unpacking operator. A merged dictionary can be created as `merged_dict = {**dict1, **dict2}`. This method creates a new dictionary without modifying the original ones. Both approaches effectively merge dictionaries, the choice between them depends on whether you want to modify an existing dictionary or produce a new merged one.
65
What is the difference between .py and .pyc files?
Reference answer
Python files that end in the py extension are text-based source files. These are the files you create when writing Python code. Python files with the pyc extension are compiled bytecode files. When a Python application runs, the interpreter looks for existing pyc files. If those do not exist, it then compiles the py source files to bytecode and runs the resulting pyc files.
66
Difference between for loop and while loop in Python
Reference answer
- For loop: Used when we know how many times to repeat, often with lists, tuples, sets or dictionaries. - While loop: Used when we only have an end condition and don't know exactly how many times it will repeat. for i in range(5): print(i) c = 0 while c < 5: print(c) c += 1 Output 0 1 2 3 4 0 1 2 3 4
67
Can we Pass a function as an argument in Python?
Reference answer
Yes, several arguments can be passed to a function, including objects, variables (of the same or distinct data types) and functions. Functions can be passed as parameters to other functions because they are objects. Higher-order functions are functions that can take other functions as arguments. def add(x, y): return x + y def apply_func(func, a, b): return func(a, b) print(apply_func(add, 3, 5)) Output 8 The add function is passed as an argument to apply_func, which applies it to 3 and 5.
68
How is memory managed in Python?
Reference answer
Memory is managed in Python in the following ways:
69
How can you remove duplicates from a list in Python?
Reference answer
You can remove duplicates from a list using various methods, including converting it to a set or using list comprehensions. For example: my_list = list(set(my_list)).
70
64. How would you describe the quicksort algorithm?
Reference answer
Quicksort is a sorting algorithm which works on divide and conquer principle. Quicksort algorithm selects a "pivot" element from the list and partitions the remaining elements into two sublists - those less than the pivot and those greater than the pivot. This process continues recursively on each sublist until the entire list is sorted. Quicksort excels at efficiently sorting the sublists because it has an average time complexity of O (n log n). It can degrade to O(n^2), in the worst case, so it's crucial to choose a good pivot strategy to optimize performance.
71
This code is supposed to create a generator that yields the first n numbers in the Fibonacci sequence. Fix the code. def fibonacci(n): a, b = 0, 1 for i in range(n): yield b a, b = b, a+b print(fibonacci(5))
Reference answer
The code is correct, but the print() statement is printing the generator object instead of the sequence of numbers. To print the sequence of numbers, you can convert the generator to a list: def fibonacci(n): a, b = 0, 1 for i in range(n): yield b a, b = b, a+b print(list(fibonacci(5)))
72
How is a class created in Python?
Reference answer
Class in Python is created using the class keyword. Example: class Employee: def __init__(self, name): self.name = name E1=Employee("abc") print(E1.name) Output: abc
73
Explain the concept of context managers and the with statement in Python.
Reference answer
Context managers allow for resource management (e.g., file I/O) using __enter__ and __exit__ methods. The with statement ensures resources are properly managed.
74
Specify the difference between local and global variables.
Reference answer
A global variable is the one declared outside of a function, in a so-called global space. All functions within the code can access such a variable. Local variables, on the other hand, are those you create within a function. Trying to access them outside the function will return a system failure.
75
Describe how to perform element-wise multiplication of two 1D arrays of different lengths using NumPy's broadcasting rules. Provide an example and explain the concept of broadcasting in NumPy.
Reference answer
import numpy as np def multiply_arrays(a, b): # Element-wise multiplication using broadcasting return a * b # Example: Multiplying arrays of different lengths array1 = np.array([1, 2, 3]) array2 = np.array([4]) # Broadcasting rules allow this operation by 'stretching' array2 # to [4, 4, 3] before performing element-wise multiplication. result = multiply_arrays(array1, array2) # Broadcasting is a powerful concept in NumPy that allows vectorized operations # on arrays of different sizes, making code efficient and concise. Explanation of solution: The function multiply_arrays performs element-wise multiplication, showcasing NumPy's broadcasting capabilities. Broadcasting automatically 'expands' smaller arrays for vectorized operations, avoiding explicit data replication and thus enhancing performance. The example illustrates how an array of length 1 (array2) is 'stretched' to match the size of array1 for multiplication, demonstrating the utility and power of broadcasting in NumPy.
76
What is the difference between a shallow copy and a deep copy?
Reference answer
| Shallow Copy | Deep Copy | |---|---| | Shallow Copy stores the references of objects to the original memory address. | Deep copy stores copies of the object's value. | | Shallow Copy reflects changes made to the new/copied object in the original object. | Deep copy doesn't reflect changes made to the new/copied object in the original object. | | Shallow Copy stores the copy of the original object and points the references to the objects. | Deep copy stores the copy of the original object and recursively copies the objects as well. | | A shallow copy is faster. | Deep copy is comparatively slower. |
77
How do you read a CSV file using Pandas?
Reference answer
To read a CSV file into a dataframe, use pd.read_csv('filename.csv') Example: import pandas as pd # Read a CSV file into a DataFrame df = pd.read_csv('data.csv') # Display the first 5 rows print(df.head())
78
How and when would you use any() and all()?
Reference answer
What is any() ? any() is a function that takes in an iterable (such as a list, tuple, set, etc.) and returns True if any of the elements evaluate to True , but it returns False if all elements evaluate to False . Passing an iterable to any() to check if any of the elements are True can be done like this: one_truth = [True, False, False] three_lies = [0, '', None] print(any(one_truth)) print(any(three_lies)) Output: True False The first print statement prints True because one of the elements in one_truth is True . On the other hand, the second print statement prints False because none of the elements are True , i.e., all elements are False . Use any() when you need to check a long series ofor conditions. What is all() ? all() is another Python function that takes in an iterable and returns True if all of the elements evaluate to True , but returns False if otherwise. Similar to any() , all() takes in a list, tuple, set, or any iterable, like so: all_true = [True, 1, 'a', object()] one_true = [True, False, False, 0] all_false = [None, '', False, 0] print(all(all_true)) print(all(one_true)) print(all(all_false)) Output: True False False The first function call returned True because all_true was filled with truthy values. Passing one_true to all() returned False because the list contained one or more falsy values. Finally, passing all_false to all() returns False because it also contained one or more falsy values. Use all() when you need to check a long series ofand conditions.
79
How can you optimize Python code performance using caching?
Reference answer
Key optimization techniques include caching results with functools.lru_cache to avoid redundant computations. For CPU-intensive tasks, you can offload computations to C extensions or libraries like NumPy and Pandas. These libraries release the GIL during heavy operations, which can significantly improve performance.
80
What are Classes and Objects ?
Reference answer
Class is a blueprint or a template that defines the structure and behavior of objects. It is like a blueprint for creating multiple instances of similar objects with shared characteristics and functionalities. It contains data (in the form of attributes or properties) and behaviors (in the form of methods or functions) that define the objects' characteristics and actions. It provides a way to organize related data and functions into a single unit. An object, on the other hand, is an instance of a class. It represents a specific entity or item created based on the class definition. Objects have their own unique state and can interact with other objects or perform operations defined within the class.
81
Why did you decide to specialize in the Python programming language?
Reference answer
Some of the reasons you'll likely want to highlight include Python's versatility and diversity of applications, its intuitive nature, and ease of use, or the use of Python by top companies including Google, YouTube, Dropbox, Quora, Mozilla, Spotify, and more. You've already proven your technical know-how when it comes to Python, so treat this as an opportunity to discuss why Python specifically interests you.
82
How do you call a function in Python?
Reference answer
You can call a function by using its name followed by parentheses, like this: def greet(name): print("Hello, " + name) greet("Alice")
83
Explain the difference between NumPy and SciPy.
Reference answer
NumPy provides support for large, multi-dimensional arrays and matrices, along with mathematical functions for array operations. SciPy builds on NumPy and offers additional modules for scientific computing, such as optimization, integration, and signal processing.
84
What is a dictionary in Python?
Reference answer
A dictionary in Python is an unordered collection of key-value pairs, where each key is unique and used to access its corresponding value. Dictionaries are mutable and defined using curly braces {}.
85
1. What is Python, and why is it popular?
Reference answer
Python is a popular computer programming language used to build softwares and web applications. Python is a general purpose programming language. It has various types of applications and is not specialized for specific problems. It's popular because of its simple syntax which makes it easy for developers to build applications. Python boasts a vast and active community that contributes to its rich library ecosystem. Python is versatile across different domains because of libraries like NumPy for numerical computations, Django for web development, and TensorFlow for machine learning. Python is a preferred language for startups and tech giants alike due to its adaptability, combined with its efficiency in rapid application development. Python's popularity is also fueled by its application in emerging fields such as data science, artificial intelligence, and automation. Python is the top preferred language for data science and research. The demand for Python developers continues to grow, making Python a sought-after skill in developer interviews, as businesses increasingly rely on data-driven insights and automation.
86
Explain the purpose of the global keyword in Python.
Reference answer
The `global` keyword is used to indicate that a variable inside a function should be treated as a global variable (i.e., it should reference the global scope). This allows you to modify global variables within a function.
87
Write Python code to print the complete contents of a file with error handling for missing files.
Reference answer
try: with open('filename','r') as file: print(file.read()) except IOError: print(“no such file exists”)
88
What is a dynamically typed language?
Reference answer
- In a dynamically typed language, the data type of a variable is determined at runtime, not at compile time. - No need to declare data types manually; Python automatically detects it based on the assigned value. - Examples of dynamically typed languages: Python, JavaScript. - Examples of statically typed languages: C, C++, Java. - Dynamically typed languages are easier and faster to code. - Statically typed languages are usually faster to execute due to type checking at compile time. Example: x = 10 # x is an integer x = "Hello" # Now x is a string Here, the type of x changes at runtime based on the assigned value hence it shows dynamic nature of Python.
89
Which Python libraries have you used for visualization?
Reference answer
Data visualization is the most important part of data analysis. You get to see your data in action, and it helps you find hidden patterns. The most popular Python data visualization libraries are: - Matplotlib - Seaborn - Plotly - Bokeh Matplotlib and Seaborn are the most common. For interactive and more complex applications, we use Plotly, which can be used to create a web application or a dashboard. Bokeh is used for detailed graphics with a high level of interactivity across large datasets.
90
Briefly explain the concept of package management in Python.
Reference answer
- Tools like pip and virtual environments help manage dependencies and versions of libraries.
91
Is Tuple Comprehension possible in Python? If yes, how and if not why?
Reference answer
Tuple comprehensions are not directly supported, Python's existing features like generator expressions and the tuple() function provide flexible alternatives for creating tuples from iterable data. (i for i in (1, 2, 3)) Explanation: In Python, expressions enclosed in parentheses with a for loop produce a generator expression, which generates values lazily one at a time. Since tuples are immutable sequences, Python does not provide a separate tuple comprehension syntax. Instead, the recommended approach is to use a generator expression and convert it into a tuple using tuple().
92
How do you write multi-line comments in Python?
Reference answer
Multi-line comments appear in more than one line. All the lines to be commented are to be prefixed by a #. You can also a very good shortcut method to comment multiple lines. All you need to do is hold the ctrl key and left click in every place wherever you want to include a # character and type a # just once. This will comment all the lines where you introduced your cursor.
93
In data science projects, data cleaning and preprocessing often consume a significant amount of time. Can you share strategies or tools you've used to handle messy data effectively?
Reference answer
Data cleaning is indeed a significant part. I've used libraries like Pandas and regular expressions for data cleaning and preprocessing. Additionally, visualization tools like Matplotlib and Seaborn help identify outliers and anomalies.
94
What are Access Specifiers in Python?
Reference answer
Python uses the '_' symbol to determine the access control for a specific data member or a member function of a class. A Class in Python has three types of Python access modifiers: - Public Access Modifier: Members declared normally (without any underscore) are public and can be accessed from anywhere. - Protected Access Modifier: Members prefixed with a single underscore (_) are intended for internal use within the class and its subclasses. They can still be accessed from outside the class, but this is discouraged by convention. - Private Access Modifier: Members prefixed with double underscores (__) are name-mangled by Python to make accidental access from outside the class more difficult. Example: class Student: def __init__(self): # Public self.name = "Mike" # Protected self._roll_no = 101 # Private self.__marks = 95 obj = Student() print(obj.name) print(obj._roll_no) print(obj._Student__marks) Output Mike 101 95 Explanation: - name is a public attribute and can be accessed directly. - _roll_no is a protected attribute, it is accessible outside the class but intended for internal use. - __marks is a private attribute and is automatically renamed internally. - obj._Student__marks accesses the private attribute using Python's name mangling mechanism.
95
What is a metaclass in Python? Provide an example of its usage.
Reference answer
A metaclass is a type of class that defines how classes will behave. Classes are instances of a metaclass, and metaclasses can define a method of creating classes that can, for instance, alter class attributes or constrain the class to a particular design pattern. Example: class Singleton(type): _instances = {} def __call__(cls, *args, **kwargs): if cls not in cls._instances: cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs) return cls._instances[cls] class MyClass(metaclass=Singleton): pass a = MyClass() b = MyClass() print(a is b) # True
96
How will you identify and deal with missing values in a dataframe?
Reference answer
We can identify if a dataframe has missing values by using the isnull() and isna() methods. missing_data_count=df.isnull().sum() We can handle missing values by either replacing the values in the column with 0 as follows: df['column_name'].fillna(0) Or by replacing it with the mean value of the column df['column_name'] = df['column_name'].fillna((df['column_name'].mean()))
97
How can elements be added to an array in Python?
Reference answer
Elements can be added to an array using the append(), extend() and the insert (i,x) functions. Example: a=arr.array('d', [1.1 , 2.1 ,3.1] ) a.append(3.4) print(a) a.extend([4.5,6.3,6.8]) print(a) a.insert(2,3.8) print(a) Output: array(‘d', [1.1, 2.1, 3.1, 3.4]) array(‘d', [1.1, 2.1, 3.1, 3.4, 4.5, 6.3, 6.8]) array(‘d', [1.1, 2.1, 3.8, 3.1, 3.4, 4.5, 6.3, 6.8])
98
What is a dynamically typed language?
Reference answer
Before we understand a dynamically typed language, we should learn about what typing is. Typing refers to type-checking in programming languages. In a strongly-typed language, such as Python, "1" + 2 will result in a type error since these languages don't allow for "type-coercion" (implicit conversion of data types). On the other hand, a weakly-typed language, such as Javascript, will simply output "12" as result. Type-checking can be done at two stages - - Static - Data Types are checked before execution. - Dynamic - Data Types are checked during execution. Python is an interpreted language, executes each statement line by line and thus type-checking is done on the fly, during execution. Hence, Python is a Dynamically Typed Language.
99
What is __init__() in Python?
Reference answer
The __init__() method is known as a constructor in object-oriented programming (OOP) terminology. It is used to initialize an object's state when it is created. This method is automatically called when a new instance of a class is instantiated. Purpose: - Assign values to object properties. - Perform any initialization operations. Example: We have created a book_shop class and added the constructor and book() function. The constructor will store the book title name and the book() function will print the book name. To test our code we have initialized the b object with “Sandman” and executed the book() function. class book_shop: # constructor def __init__(self, title): self.title = title # Sample method def book(self): print('The title of the book is', self.title) b = book_shop('Sandman') b.book() # The title of the book is Sandman
100
Name the fundamental Python features.
Reference answer
- Interpreted language. Unlike C, there's no need to compile Python code before running it. - Object-oriented language. Like Java and other OOP technologies, Python supports inheritance and class definition. On the other hand, there's no support for access specifiers (e.g., public, private in C++). - Code execution is slower than that of compiled languages. To find their way around the issue, developers use packages like NumPy.
101
How will you find the nearest value in a given numpy array?
Reference answer
We can use the argmin() method of numpy as shown below: import numpy as np def find_nearest_value(arr, value): arr = np.asarray(arr) idx = (np.abs(arr - value)).argmin() return arr[idx] #Driver code arr = np.array([ 0.21169, 0.61391, 0.6341, 0.0131, 0.16541, 0.5645, 0.5742]) value = 0.52 print(find_nearest_value(arr, value)) # Prints 0.5645
102
How can microservices be implemented with Python?
Reference answer
Microservices are a popular architectural style for building scalable systems, and Python is an excellent choice for developing them. Key aspects include: Choosing the Right Framework: Python offers frameworks like Flask (lightweight for small services), FastAPI (designed for performance with modern features), and Django REST framework (powerful with admin interface and ORM). Containerization: Docker is common for containerizing Python microservices, ensuring consistent environments across development stages and reducing 'it works on my machine' issues. Asynchronous Programming: Using asyncio and frameworks like Tornado can greatly enhance performance of I/O-bound microservices by handling concurrent connections efficiently. Testing: Automated testing with Pytest or Unittest is crucial to ensure each service functions correctly in isolation and when interacting with others. Inter-service Communication: Use HTTP/REST, gRPC, or messaging queues like RabbitMQ. Libraries like requests or httpx for HTTP, and pika for RabbitMQ. Monitoring and Logging: Use Python's logging module and comprehensive solutions like Prometheus or Elastic Stack. Deployment and Scaling: Use Kubernetes for orchestrating containerized applications. Security: Leverage built-in security features, use HTTPS, secure inter-service communications, and manage sensitive data securely.
103
61. What is Big O notation, and why is it important?
Reference answer
Big O notation is a mathematical notation used to describe the time complexity of algorithms. Big O notation gives insights into which solution is more scalable or efficient in the worst-case scenario, when comparing different algorithms for a problem. For example, a solution with a complexity of O(n^2) will perform worse than one with O(n) for large datasets. Recognizing and optimizing the complexity of algorithms is vital, especially when handling large amounts of data in Python applications. Big O notation is fundamental in assessing algorithm performance. For Python developers, mastering this concept ensures optimal code design, making it a frequent topic in technical interviews.
104
Design a class to represent and manipulate complex data structures like graphs
Reference answer
class Graph: def __init__(self): self.vertices = {} def add_vertex(self, vertex): if vertex not in self.vertices: self.vertices[vertex] = [] def add_edge(self, u, v): if u in self.vertices and v in self.vertices: self.vertices[u].append(v) self.vertices[v].append(u) def display(self): for vertex in self.vertices: print(f'{vertex}: {self.vertices[vertex]}')
105
How is memory managed in Python?
Reference answer
- Memory management in Python is handled by the Python Memory Manager. The memory allocated by the manager is in form of a private heap space dedicated to Python. All Python objects are stored in this heap and being private, it is inaccessible to the programmer. Though, python does provide some core API functions to work upon the private heap space. - Additionally, Python has an in-built garbage collection to recycle the unused memory for the private heap space.
106
Explain how you would handle time series data in Pandas.
Reference answer
- Use DatetimeIndex, resampling, rolling statistics, and specialized plotting functions.
107
In Python, how can I reverse a string?
Reference answer
You can reverse a string using slicing: s = "Python" reversed_s = s[::-1] print(reversed_s) # Output: 'nohtyP'
108
What is lambda in Python? Why is it used?
Reference answer
Lambda is an anonymous function in Python, that can accept any number of arguments, but can only have a single expression. It is generally used in situations requiring an anonymous function for a short time period. Lambda functions can be used in either of the two ways: - Assigning lambda functions to a variable: mul = lambda a, b : a * b print(mul(2, 5)) # output => 10 - Wrapping lambda functions inside another function: def myWrapper(n): return lambda a : a * n mulFive = myWrapper(5) print(mulFive(2)) # output => 10
109
What are negative indexes in Python?
Reference answer
All programming languages use positive indexing in the arrays to locate and access elements. Python is the only language that allows both positive and negative indexing in arrays. A positive index would start from the first element of an array and go forward i.e. the first element would be 0, the second element would be 1, and so on. In negative indexing, the last element of the array would have the index -1, the penultimate element would be -2, and so on. For example, arr = [a, b, c, d, e] print(arr[-1]) print(arr[-2]) Output e d
110
What is __init__() in Python and how does self play a role in it?
Reference answer
- __init__() is Python's equivalent of constructors in OOP, called automatically when a new object is created. It initializes the object's attributes with values but doesn't handle memory allocation. - Memory allocation is handled by the __new__() method, which is called before __init__(). - The self parameter in __init__() refers to the instance of the class, allowing access to its attributes and methods. - self must be the first parameter in all instance methods, including __init__() class MyClass: def __init__(self, value): self.value = value # Initialize object attribute def display(self): print(f"Value: {self.value}") obj = MyClass(10) obj.display() Output Value: 10
111
96. How do you explain the concept of unit testing in Python?
Reference answer
Unit testing in Python refers to the process of testing individual units or components of a software. These units are the smallest testable parts of an application, isolated from the rest of the code. The `unittest` module provides tools to create and run tests. Writing tests involves creating test cases that assert certain conditions. The tested unit functions as expected, When these assertions pass. For example, testing a function that adds two numbers would involve writing a test that checks if the function returns the correct sum. Failures indicate defects in the code or the test itself. Conducting unit tests aids developers in ensuring code quality. It identifies bugs early, simplifies integration, and facilitates refactoring. Proper unit testing increases the reliability of the software and reduces the likelihood of errors in production.
112
How would you achieve memoization in Python?
Reference answer
Consider this computationally expensive code: # Fibonacci Numbers def fib(num): if num == 0: return 0 elif num == 1: return 1 return fib(num - 1) + fib(n - 2) Memoization can be achieved through Python decorators Here's the full implementation. import timeit def memoize_fib(func): cache = {} def inner(arg): if arg not in cache: cache[arg] = func(arg) return cache[arg] return inner def fib(num): if num == 0: return 0 elif num == 1: return 1 else: return fib(num-1) + fib(num-2) fib = memoize_fib(fib) print(timeit.timeit('fib(30)', globals=globals(), number=1)) print(timeit.timeit('fib(30)', globals=globals(), number=1)) print(timeit.timeit('fib(30)', globals=globals(), number=1)) Output: 4.9035000301955733e-05 1.374000021314714e-06 1.2790005712304264e-06
113
What is the purpose of Python non-local statements?
Reference answer
Non-local statements allow assigning variables to outer-scope statements that are not global. The most common application of the keyword is in nested functions, where there's a need to make sure a variable isn't accessible by the inner function.
114
The following code is supposed to create a dictionary with the keys and values reversed from the original dictionary. What is wrong with the code, and how can it be fixed? original_dict = {"one": 1, "two": 2, "three": 3} reversed_dict = {} for key, value in original_dict.items(): reversed_dict[value] = key print(reversed_dict)
Reference answer
The code is correct.
115
What is lambda in Python?
Reference answer
This is the small anonymous function used in Python as an inline function. An example of lambda function is: lambda arguments : expression
116
Find all permutations of a text field
Reference answer
Output : Permutations of "ABC" is as below, ABC ACB BAC BCA CAB CBA
117
What is the difference between a list and a NumPy array in Python?
Reference answer
Lists are built-in Python data structures that can hold elements of different data types, while NumPy arrays are homogeneous arrays of fixed size and contiguous memory. NumPy arrays also support vectorized operations and mathematical functions, making them more efficient for numerical operations.
118
Implement breadth first search (BFS) in Python
Reference answer
Consider the graph which is implemented in the code below: graph = { 'A' : ['B','C'], 'B' : ['D', 'E'], 'C' : ['F'], 'D' : [], 'E' : ['F'], 'F' : [] } visited = [] # List to keep track of visited nodes. queue = [] #Initialize a queue def bfs(visited, graph, node): visited.append(node) queue.append(node) while queue: s = queue.pop(0) print (s, end = " ") for neighbour in graph[s]: if neighbour not in visited: visited.append(neighbour) queue.append(neighbour) # Driver Code bfs(visited, graph, 'A') Output: A B C D E F Explanation Lines 3-10: The illustrated graph is represented using an adjacency list. An easy way to do this in Python is to use a dictionary data structure, where each vertex has a stored list of its adjacent nodes. Line 12: visited is a list that is used to keep track of visited nodes. Line 13: queue is a list that is used to keep track of nodes currently in the queue. Line 29: The arguments of the bfs function are the visited list, the graph in the form of a dictionary, and the starting node A . Lines 15-26: bfs follows the algorithm described above: - It checks and appends the starting node to the visited list and thequeue . - Then, while the queue contains elements, it keeps taking out nodes from the queue, appends the neighbors of that node to the queue if they are unvisited, and marks them as visited. - This continues until the queue is empty. Time Complexity Since all of the nodes and vertices are visited, the time complexity for BFS on a graph is O(V + E); where V is the number of vertices and E is the number of edges.
119
What is PEP 8?
Reference answer
PEP 8 is Python's style guide for writing clean and readable code. It includes conventions such as indentation (4 spaces per level), naming variables in snake_case, and avoiding line length exceeding 79 characters. It ensures consistency across Python projects.
120
Reverse a String
Reference answer
Output : Using String slicing : DASARP Using for loop : DASARP
121
How do you convert a string to an integer in python?
Reference answer
The Python int function will convert a string to an integer. The second parameter is for the base of the number, so 10 for decimal numbers. x = '100' int(x, 10)
122
How do you convert a list of strings to uppercase?
Reference answer
Sample Answer: To convert a list of strings to uppercase, you can iterate through the list and convert each string to uppercase using Python's str.upper() method. For example: def to_uppercase(strings): return [s.upper() for s in strings]
123
33. How to implement a binary search algorithm in Python?
Reference answer
A binary search algorithm in Python is implemented by repeatedly dividing the sorted list in half until the desired element is found or the whole list is exhausted. To begin with, define three pointers: `low` , `high` , and `mid` . Set `low` to 0 and `high` to the length of the list minus one. In each iteration, calculate `mid` as the average of `low` and `high` . Compare the mid-value with the target. If the target is equal to the mid-value, return `mid` . If the target is less than the mid-value, update `high` to `mid - 1` . If the target is greater, set `low` to `mid + 1` . Continue the process until `low` exceeds `high` or the target is found. If the list does not contain the target, return an indication of failure, such as -1. This algorithm works efficiently for sorted lists, reducing the search space by half in each step.
124
Write a Python code to pivot a dataframe?
Reference answer
- df.pivot() reshapes the DataFrame by setting date as the index, category as columns, and value as the data to fill the new table. import pandas as pd # Sample data data = { 'date': ['2023-01-01', '2023-01-01', '2023-01-02', '2023-01-02'], 'category': ['A', 'B', 'A', 'B'], 'value': [10, 20, 15, 25] } # Creating DataFrame df = pd.DataFrame(data) # Pivoting the DataFrame pivot_df = df.pivot(index='date', columns='category', values='value') # Display the pivoted DataFrame print(pivot_df)
125
Write a simple Python program to print an output.
Reference answer
print("Hello, World!") Output Hello, World!
126
Explain the purpose of the contextlib module and how it is used for managing resources in Python.
Reference answer
The `contextlib` module provides utilities for creating and working with context managers using the `with` statement.
127
How can you check if two IP addresses are in the same subnet in Python?
Reference answer
we first have to convert all the IP addresses and the netmask to integers using the ip_to_int function from earlier. Then, we have to use the bitwise AND operator (&) to mask out the subnet portion of the IP addresses, and compare the results. If they are equal, the two IP addresses are in the same subnet.
128
What are the common built-in data types in Python?
Reference answer
There are several built-in data types in Python. Although, Python doesn't require data types to be defined explicitly during variable declarations type errors are likely to occur if the knowledge of data types and their compatibility with each other are neglected. Python provides type() and isinstance() functions to check the type of these variables. These data types can be grouped into the following categories- - None Type: None keyword represents the null values in Python. Boolean equality operation can be performed using these NoneType objects. | Class Name | Description | |---|---| | NoneType | Represents the NULL values in Python. | - Numeric Types: There are three distinct numeric types - integers, floating-point numbers, and complex numbers. Additionally, booleans are a sub-type of integers. | Class Name | Description | |---|---| | int | Stores integer literals including hex, octal and binary numbers as integers | | float | Stores literals containing decimal values and/or exponent signs as floating-point numbers | | complex | Stores complex numbers in the form (A + Bj) and has attributes: real and imag | | bool | Stores boolean value (True or False). | Note: The standard library also includes fractions to store rational numbers and decimal to store floating-point numbers with user-defined precision. - Sequence Types: According to Python Docs, there are three basic Sequence Types - lists, tuples, and range objects. Sequence types have the in and not in operators defined for their traversing their elements. These operators share the same priority as the comparison operations. | Class Name | Description | |---|---| | list | Mutable sequence used to store collection of items. | | tuple | Immutable sequence used to store collection of items. | | range | Represents an immutable sequence of numbers generated during execution. | | str | Immutable sequence of Unicode code points to store textual data. | Note: The standard library also includes additional types for processing: 1. Binary data such as bytearray bytes memoryview, and 2. Text strings such as str. - Mapping Types: A mapping object can map hashable values to random objects in Python. Mappings objects are mutable and there is currently only one standard mapping type, the dictionary. | Class Name | Description | |---|---| | dict | Stores comma-separated list of key: value pairs | - Set Types: Currently, Python has two built-in set types - set and frozenset. set type is mutable and supports methods like add() and remove(). frozenset type is immutable and can't be modified after creation. | Class Name | Description | |---|---| | set | Mutable unordered collection of distinct hashable objects. | | frozenset | Immutable collection of distinct hashable objects. | Note: set is mutable and thus cannot be used as key for a dictionary. On the other hand, frozenset is immutable and thus, hashable, and can be used as a dictionary key or as an element of another set. - Modules: Module is an additional built-in type supported by the Python Interpreter. It supports one special operation, i.e., attribute access: mymod.myobj, where mymod is a module and myobj references a name defined in m's symbol table. The module's symbol table resides in a very special attribute of the module __dict__, but direct assignment to this module is neither possible nor recommended. - Callable Types: Callable types are the types to which function call can be applied. They can be user-defined functions, instance methods, generator functions, and some other built-in functions, methods and classes. Refer to the documentation at docs.python.org for a detailed view of the callable types.
129
Explain the purpose of the zip and map functions in Python, and provide examples of their usage.
Reference answer
`zip` combines iterables element-wise, and `map` applies a function to elements of iterables. For example, `zip([1, 2], [3, 4])` returns `[(1, 3), (2, 4)]` ```, and` map(lambda x: x*2, [1, 2, 3]) `returns` [2, 4, 6] ```.
130
How do you create a class in Python?
Reference answer
To create a class in python, we use the keyword "class" as shown in the example below: class InterviewbitEmployee: def __init__(self, emp_name): self.emp_name = emp_name To instantiate or create an object from the class created above, we do the following: emp_1=InterviewbitEmployee("Mr. Employee") To access the name attribute, we just call the attribute using the dot operator as shown below: print(emp_1.emp_name) # Prints Mr. Employee To create methods inside the class, we include the methods under the scope of the class as shown below: class InterviewbitEmployee: def __init__(self, emp_name): self.emp_name = emp_name def introduce(self): print("Hello I am " + self.emp_name) The self parameter in the init and introduce functions represent the reference to the current class instance which is used for accessing attributes and methods of that class. The self parameter has to be the first parameter of any method defined inside the class. The method of the class InterviewbitEmployee can be accessed as shown below: emp_1.introduce() The overall program would look like this: class InterviewbitEmployee: def __init__(self, emp_name): self.emp_name = emp_name def introduce(self): print("Hello I am " + self.emp_name) # create an object of InterviewbitEmployee class emp_1 = InterviewbitEmployee("Mr Employee") print(emp_1.emp_name) #print employee name emp_1.introduce() #introduce the employee
131
This code is supposed to return a list of all odd numbers from the input list. Fix the code. def get_odd_numbers(nums): odd_nums = filter(lambda num: num % 2) return list(odd_nums) nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] print(get_odd_numbers(nums))
Reference answer
The lambda function inside the filter() function is missing the argument nums in the expression. The corrected code is: def get_odd_numbers(nums): odd_nums = filter(lambda num: num % 2, nums) return list(odd_nums) nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] print(get_odd_numbers(nums))
132
How can you work with databases in Python, and what are some commonly used database libraries and frameworks?
Reference answer
Python offers various database libraries like SQLAlchemy and Django ORM. You can connect to databases, execute queries, and perform CRUD operations.
133
What do we mean when we say that a certain Lambda expression forms a closure?
Reference answer
A closure is a lambda (or nested function) that captures variables from its enclosing scope, even after that scope has finished executing. For example, lambda x: x + y forms a closure if y is defined in an outer scope and the lambda retains access to it.
134
When should you use lambda functions in Python?
Reference answer
Use lambda functions when an anonymous function is required for a short period of time.
135
What is the purpose of the if __name__ == "__main__": statement in Python scripts?
Reference answer
The if __name__ == "__main__": statement checks whether the Python script is being run as the main program. It allows you to separate the code that should only run when the script is executed directly from the code that should be used when the script is imported as a module. if __name__ == "__main__": # Code here will only run if the script is executed directly print("Hello, world!")
136
What are data frames?
Reference answer
Data frames are two-dimensional, labeled data structures in Python, commonly used in the pandas library. They resemble spreadsheets or SQL tables and allow for efficient data manipulation, analysis, and storage.
137
Write a Python function to check if a number is a prime factor of another number.
Reference answer
Solution: def is_prime_factor(number, potential_factor): if number <= 1 or potential_factor <= 1: return False # Numbers less than or equal to 1 are not considered prime factors return number % potential_factor == 0 # Example usage number = 15 potential_factor = 3 if is_prime_factor(number, potential_factor): print(potential_factor, "is a prime factor of", number) else: print(potential_factor, "is not a prime factor of", number) Output: 3 is a prime factor of 15
138
What is the difference between yield and return in Python?
Reference answer
In Python, ‘return' sends a value and terminates a function, while ‘yield' produces a value but retains the function's state, allowing it to resume from where it left off. | YIELD | RETURN | | It replace the return of a function to suspend its execution without destroying local variables. | It exits from a function and handing back a value to its caller. | | It is used when the generator returns an intermediate result to the caller. | It is used when a function is ready to send a value. | | Code written after yield statement execute in next function call. | while, code written after return statement wont execute. | | It can run multiple times. | It only runs single time. | | Yield statement function is executed from the last state from where the function get paused. | Every function calls run the function from the start.
139
What is the time complexity of a recursion function in python?
Reference answer
The time complexity of recursion depends on the number of times the function calls itself. If a function calls itself two times then its time complexity is O(2 ^ N). if it calls three times, then its time complexity is O(3 ^ N) and so on.
140
What is the join method in python?
Reference answer
The join method in Python takes elements of an iterable data structure and connects them together using a particular string connector value. How does join work? The join method in Python is a string method, which connects elements of a string iterable structure, which also contains strings or characters (array, list, etc.) by using a particular string as the connector. Example: Connecting elements using an empty string This will join the elements in an array using an empty string between each element. array = ['H','E','L','L','O'] connector = "" joined_string = connector.join(array) print(joined_string) Output: HELLO
141
Can you tell us what is slicing in Python?
Reference answer
Slicing in Python is about dividing a given string to obtain sub-strings. If you wish to access sequences such as lists, tuples, and strings, slicing is the feature that will help you do so. You can select a specific range or part of these sequences using slicing. You can change or delete parts of sequences like lists that can be changed. Slicing in Python helps you write clean, precise, and readable code. You can perform slicing in Python by either extending indexing or using the slice() Constructor.
142
What is the docstring in python?
Reference answer
Python documentation strings (or docstrings) provide a convenient way of associating documentation with Python modules, functions, classes, and methods.
143
Explain the use of Python's built-in map, filter, and reduce functions, and provide examples of their usage.
Reference answer
`map` applies a function to elements of an iterable, `filter` filters elements based on a function```'s result, and reduce` applies a function cumulatively to elements of an iterable.``
144
How can you handle exceptions in Python?
Reference answer
In Python, you can handle exceptions using the try, except, else, and finally blocks. The try block contains the code that may raise an exception. If an exception occurs, it is caught by the corresponding except block. The else block is executed if no exception occurs, and the finally block is executed regardless of whether an exception occurred or not.
145
Why can x = x + [1] behave differently than x += [1]?
Reference answer
x = x + [1] creates a new list and assigns it to x, while x += [1] changes the same list in place, this matters when other variables point to the same list, because one keeps the old list and the other sees the change. a = [1, 2] b = a a = a + [3] print(b) # [1, 2] a = [1, 2] b = a a += [3] print(b) # [1, 2, 3]
146
86. How do you explain session management in Python web applications?
Reference answer
Session management is the process of tracking and managing the state of a user's interaction with a web application. Session management includes the user's login status, preferences, etc. Session management in Python web applications refers to the process of preserving user data across multiple requests. This mechanism ensures that a user does not need to re-authenticate or re-enter data on every page or action. Flask and Django, offer built-in tools for this purpose. Flask uses a secure cookie-based session system by default. Django employs a database-driven session system. A unique session ID is generated and sent to the client's browser, when a user logs in. This ID serves as a reference to the user's stored data on the server. Session management facilitates a seamless user experience. Web applications would not provide continuity or remember individual user interactions across pages.
147
How do you install Pandas in Python?
Reference answer
You can install Pandas using pip by running the command pip install pandas.
148
Can you get items of series A that are not available in another series B?
Reference answer
This can be achieved by using the ~ (not/negation symbol) and isin() method as shown below. import pandas as pd df1 = pd.Series([2, 4, 8, 10, 12]) df2 = pd.Series([8, 12, 10, 15, 16]) df1=df1[~df1.isin(df2)] print(df1) """ Output: 0 2 1 4 dtype: int64 """
149
What is Pandas aggregation?
Reference answer
Pandas aggregation is the process of summarizing data by computing statistical measures like mean, median, mode, standard deviation, etc., on a group of rows in a dataframe.
150
16. What is Object-Oriented Programming, and how is it implemented in Python?
Reference answer
Object-Oriented Programming (OOP) is a programming paradigm that uses objects and classes to design and structure code. Objects represent real-world entities and the interactions between them in OOP. Python fully supports Object-Oriented Programming (OOP). It allows developers to define classes, create objects, and work with inheritance, polymorphism, and encapsulation. Everything is an object in Python, even basic data types like integers and strings. A class in Python is defined using the `class` keyword. Objects of that class can be instantiated once it is defined. Inheritance allows a class to inherit attributes and methods from another class, enabling code reuse and establishing relationships between classes. Methods in Python can be overridden in derived classes, showcasing polymorphism. Encapsulation is achieved by using private and protected access specifiers, though it's more of a convention in Python. Python offers a rich set of tools and constructs for OOP, making it easy for developers to model and solve complex problems using objects and classes.
151
What is a zip function?
Reference answer
Python zip() function returns a zip object, which maps a similar index of multiple containers. It takes an iterable, converts it into an iterator and aggregates the elements based on iterables passed. It returns an iterator of tuples. Syntax: zip(*iterables)
152
What are functions and how do you define them?
Reference answer
- Reusable blocks of code that take arguments and perform specific tasks. - Defined with def: def function_name(parameters): # code block return value
153
What are lambda functions?
Reference answer
Lambda functions are generally inline, anonymous functions represented by a single expression. They are used for creating function objects during runtime. They can accept any number of parameters. They are usually used where functions are required only for a short period. They can be used as: mul_func = lambda x,y : x*y print(mul_func(6, 4)) # Output: 24
154
What are Membership Operators?
Reference answer
Membership operators are used to test if a sequence is present in an object. The in and not in operators are examples of these: x = ["apple", "banana"] print("banana" in x) # returns True x = ["apple", "banana"] print("pineapple" not in x) # returns True
155
How do you split a string into a list of words?
Reference answer
Use the split() method, which divides a string by whitespace by default: sentence = "Hello World" words = sentence.split() print(words) # Output: ['Hello', 'World']
156
What is Python Switch Statement?
Reference answer
Python does not have a traditional switch statement like languages such as C, C++ or Java. Starting with Python 3.10, however, Python introduced structural pattern matching using the match and case keywords, which provides similar functionality. match term: case pattern-1: action-1 case pattern-2: action-2 case pattern-3: action-3 case _: action-default
157
What are some real life applications of Python ?
Reference answer
Python is widely used for the following fields: - Web Scraping Applications. - Data Science. - Artificial Intelligence and Machine Learning. - Game Development. - Software Development - Web Development, etc.
158
Detect loop in a linked list
Reference answer
To see the code solution in action, visit the original post. Explanation Iterate over the whole linked list and add each visited node to a visited_nodes set. At every node, we check whether it has been visited or not. By principle, if a node is revisited, a cycle exists! Time Complexity We iterate the list once. On average, lookup in a set takes O(1) time. Hence, the average runtime of this algorithm is O(n). However, in the worst case, lookup can increase up to O(n), which would cause the algorithm to work in
159
What is docstring in Python?
Reference answer
- Documentation string or docstring is a multiline string used to document a specific code segment. - The docstring should describe what the function or method does.
160
What is the MultiIndex feature in Pandas, and when is it used?
Reference answer
`MultiIndex` is a feature in Pandas that allows you to have multiple levels of row and column labels in a DataFrame. It is used when dealing with complex, hierarchical data.
161
Explain inheritance in Python with an example
Reference answer
Inheritance allows One class to gain all the members(say attributes and methods) of another class. Inheritance provides code reusability, makes it easier to create and maintain an application. The class from which we are inheriting is called super-class and the class that is inherited is called a derived / child class. They are different types of inheritance supported by Python: - Single Inheritance – where a derived class acquires the members of a single super class. - Multi-level inheritance – a derived class d1 in inherited from base class base1, and d2 are inherited from base2. - Hierarchical inheritance – from one base class you can inherit any number of child classes - Multiple inheritance – a derived class is inherited from more than one base class.
162
How do you handle exceptions in Python?
Reference answer
Use try-except blocks for handling exceptions. Example: try: result = 10 / 0 except ZeroDivisionError as e: print(f"Error: {e}") finally: print("This always executes.")
163
How can you generate random numbers in Python?
Reference answer
Random module is the standard module that is used to generate a random number. The method is defined as: import random random.random The statement random.random() method return the floating-point number that is in the range of [0, 1). The function generates random float numbers. The methods that are used with the random class are the bound methods of the hidden instances. The instances of the Random can be done to show the multi-threading programs that creates a different instance of individual threads. The other random generators that are used in this are:
164
How do you define a default parameter value in a function?
Reference answer
You can specify default values for parameters in the function definition, like this: def greet(name="Guest"): print("Hello, " + name)
165
What is late binding in Python closures (lambda in loops issue)?
Reference answer
Late binding means variables in a function are looked up when the function is called, not when it is created, so in a loop, all lambdas end up using the last value of the loop variable, which gives wrong results, the fix is to pass the value as a default argument. funcs = [] for i in range(3): funcs.append(lambda: i) for f in funcs: print(f()) # 2 2 2 funcs = [] for i in range(3): funcs.append(lambda i=i: i) for f in funcs: print(f()) # 0 1 2
166
Write a program for counting the number of every character of a given text file.
Reference answer
The idea is to use collections and pprint module as shown below: import collections import pprint with open("sample_file.txt", 'r') as data: count_data = collections.Counter(data.read().upper()) count_value = pprint.pformat(count_data) print(count_value)
167
Design a Django model Book with fields for title (a string), author (a string), and publication_date (a date). Show how you would create a new instance of this model in the Django shell.
Reference answer
from django.db import models class Book(models.Model): title = models.CharField(max_length=100) author = models.CharField(max_length=100) publication_date = models.DateField() # Creating an instance in the Django shell # from myapp.models import Book # book = Book(title='Sample Book', author='Author Name', publication_date='2023-01-01') # book.save() Explanation of solution: The Book model is defined with three fields: title, author, and publication_date. The model is a subclass of django.db.models.Model. An example is provided for creating an instance of Book in the Django shell, including saving it to the database.
168
Explain the difference between lists and tuples in Python.
Reference answer
- Lists: Mutable -- elements can be changed after creation. Use square brackets ([]). - Tuples: Immutable -- elements cannot be changed after creation. Use parentheses (()).
169
Are there any tools for identifying bugs and performing static analysis in python?
Reference answer
Yes, there are tools like PyChecker and Pylint which are used as static analysis and linting tools respectively. PyChecker helps find bugs in python source code files and raises alerts for code issues and their complexity. Pylint checks for the module's coding standards and supports different plugins to enable custom features to meet this requirement.
170
What is pickling and unpickling?
Reference answer
Python library offers a feature - serialization out of the box. Serializing an object refers to transforming it into a format that can be stored, so as to be able to deserialize it, later on, to obtain the original object. Here, the pickle module comes into play. Pickling: - Pickling is the name of the serialization process in Python. Any object in Python can be serialized into a byte stream and dumped as a file in the memory. The process of pickling is compact but pickle objects can be compressed further. Moreover, pickle keeps track of the objects it has serialized and the serialization is portable across versions. - The function used for the above process is pickle.dump(). Unpickling: - Unpickling is the complete inverse of pickling. It deserializes the byte stream to recreate the objects stored in the file and loads the object to memory. - The function used for the above process is pickle.load(). Note: Python has another, more primitive, serialization module called marshall, which exists primarily to support .pyc files in Python and differs significantly from the pickle.
171
38. How to remove duplicates from a list in Python?
Reference answer
Duplicates from a list in Python are removed using the set data structure. Transform the list into a set, which inherently doesn't allow duplicate values. Once the duplicates are removed, convert the set back to a list. For example, if you have a list named `my_list`, you can obtain a duplicate-free list with `list(set(my_list))`. It will not preserve the original order of the list, using this method. You can use list comprehensions,to retain the order, Iterate over the list and add each item to the new list only if it hasn't been added before. Opt for the method that best suits the requirements of your application, be it order preservation or computational efficiency.
172
Can you create a series from the dictionary object in pandas?
Reference answer
One dimensional array capable of storing different data types is called a series. We can create pandas series from a dictionary object as shown below: import pandas as pd dict_info = {'key1' : 2.0, 'key2' : 3.1, 'key3' : 2.2} series_obj = pd.Series(dict_info) print (series_obj) Output: x 2.0 y 3.1 z 2.2 dtype: float64 If an index is not specified in the input method, then the keys of the dictionaries are sorted in ascending order for constructing the index. In case the index is passed, then values of the index label will be extracted from the dictionary.
173
How do you manage dependencies in Python projects?
Reference answer
Dependencies can be managed using: - pip: For installing and managing packages. - requirements.txt: Lists all dependencies for a project. - Virtual environments: Tools like venv or virtualenv isolate dependencies. Example: bash pip install -r requirements.txt
174
Find the middle value of the linked list
Reference answer
To see the code solution in action, go to the original post. Here you can use two pointers which will work simultaneously. Think of it this way: - The fast pointer moves two steps at a time till the end of the list - The slow pointer moves one step at a time - When the fast pointer reaches the end, the slow pointer will be at the middle Using this algorithm, you can make the process faster because the calculation of the length and the traversal until the middle are happening side-by-side. Time Complexity You are traversing the linked list at twice the speed, so it is certainly faster. However, the bottleneck complexity is still O(n).
175
How do you install Python on your computer?
Reference answer
You can download Python from the official website (python.org) and follow the installation instructions for your operating system.
176
How do you find the intersection of two sorted arrays?
Reference answer
Sample Answer: Finding the intersection of two sorted arrays involves identifying the common elements that appear in both arrays. This can be efficiently achieved using a two-pointer technique, where you maintain a pointer for each array and move them based on the comparison of the elements. Here's the code to find the intersection of two sorted arrays: def intersection_sorted(arr1, arr2): result = [] i, j = 0, 0 while i < len(arr1) and j < len(arr2): if arr1[i] < arr2[j]: i += 1 elif arr1[i] > arr2[j]: j += 1 else: result.append(arr1[i]) i += 1 j += 1 return result
177
Detecting a Cycle in a Linked List: How do you detect a cycle using slow/fast pointers?
Reference answer
You move one pointer one step at a time and another two steps at a time, if there is a cycle they will meet, if the fast pointer reaches the end then there is no cycle, this uses no extra memory and is very efficient. def has_cycle(head): slow = fast = head while fast and fast.next: slow = slow.next fast = fast.next.next if slow == fast: return True return False
178
What is the Python "with" statement designed for?
Reference answer
The with statement is used for exception handling to make code cleaner and simpler. It is generally used for the management of common resources like creating, editing, and saving a file. Example: Instead of writing multiple lines of open, try, finally, and close, you can create and write a text file using the with statement. It is simple. # using with statement with open('myfile.txt', 'w') as file: file.write('DataCamp Black Friday Sale!!!')
179
What is slicing in Python?
Reference answer
Slicing is used to access parts of sequences like lists, tuples, and strings. The syntax of slicing is-[start:end:step]. The step can be omitted as well. When we write [start:end] this returns all the elements of the sequence from the start (inclusive) till the end-1 element. If the start or end element is negative i, it means the ith element from the end. The step indicates the jump or how many elements have to be skipped. Eg. if there is a list- [1,2,3,4,5,6,7,8]. Then [-1:2:2] will return elements starting from the last element till the third element by printing every second element.i.e. [8,6,4].
180
What's the difference between __str__ and __repr__ in Python?
Reference answer
__str__ returns a user-friendly string representation of an object, while __repr__ returns an unambiguous string representation, typically one that could recreate the object.
181
What is a list in Python?
Reference answer
A list in python is an ordered collection of items. It can hold elements of different data types.
182
What is the Global Interpreter Lock (GIL) in Python, and how does it impact multithreading?
Reference answer
The Global Interpreter Lock (GIL) is a mechanism in CPython (the standard implementation of Python) that allows only one thread to execute Python bytecode at a time. This means that even on multi-core systems, Python threads cannot fully utilize multiple CPU cores for CPU-bound tasks. However, the GIL doesn't impact performance much for I/O-bound tasks, making multithreading beneficial in such scenarios.
183
What does the capitalize() method do in Python?
Reference answer
In Python, the capitalize() method capitalizes the first letter of a string. If the string already consists of a capital letter at the beginning, then, it returns the original string.
184
What are Python's data types?
Reference answer
- Numeric types: int, float, complex - Sequence types: list, tuple, range - Text type: str - Set types: set, frozenset - Mapping type: dict - Boolean type: bool - Binary types: bytes, bytearray, memoryview
185
How do you open and read a file in Python?
Reference answer
To open and read a file in Python, you can use the open() function with the appropriate file mode (e.g., r' for reading). For example: with open(example.txt', r') as file: content = file.read()
186
How is an empty class created in python?
Reference answer
An empty class does not have any members defined in it. It is created by using the pass keyword (the pass command does nothing in python). We can create objects for this class outside the class. For example- class EmptyClassDemo: pass obj=EmptyClassDemo() obj.name="Interviewbit" print("Name created= ",obj.name) Output: Name created = Interviewbit
187
85. What are cookies, and how does Python handle them in web development?
Reference answer
Cookies are small pieces of data stored on a user's browser by websites. They help websites remember user preferences, login details, and other information to improve user experience. The `http.cookies` module provides tools for working with cookies. Python web frameworks like Flask and Django have built-in mechanisms for handling cookies. For instance, you use `request.cookies` to read cookies and `response.set_cookie` to set them in Flask. Django provides a similar interface through its `request.COOKIES` attribute and the `set_cookie` method on its HttpResponse object. Cookies play a crucial role in maintaining session states and personalizing user interactions in web development. Python, with its rich ecosystem, facilitates smooth cookie management in web applications.
188
How would you use regular expressions in Python? Provide an example.
Reference answer
Use the re module to compile and search patterns. Example: re.findall(r'\b\w{3}\b', text) finds all three-letter words in a text.
189
How to reverse the rows of a data frame?
Reference answer
To reverse the rows of a pandas DataFrame, use the iloc[] indexer with [::-1] to reverse row order, e.g., df_reversed = df.iloc[::-1]. Alternatively, use df.sort_index(ascending=False) or df.reindex(index=df.index[::-1]).
190
Explain the concept of context managers in Python, and how are they typically used?
Reference answer
Context managers, implemented with ` ```with``` ` statements, manage resources like files and database connections, ensuring they``'re properly acquired and released.
191
How do you handle HTTP status codes in API responses?
Reference answer
Always check the status_code member variable on the response object and handle things according to the code. Example: import requests response = requests.get('https://api.example.com/data') if response.status_code == 200: print("Success") elif response.status_code == 404: print("Not Found") else: print(f"Error: {response.status_code}")
192
Multiple Choice Question: When will the file be closed in the following code? f = None for i in range (5): with open("data.txt", "w") as f: if (i > 2): break print f.closed a) True b) False c) None d) Error
Reference answer
Answer: a) True The WITH statement when used with open file guarantees that the file object is closed when the with block exits.
193
What do you know about pandas?
Reference answer
- Pandas is an open-source, python-based library used in data manipulation applications requiring high performance. The name is derived from "Panel Data" having multidimensional data. This was developed in 2008 by Wes McKinney and was developed for data analysis. - Pandas are useful in performing 5 major steps of data analysis - Load the data, clean/manipulate it, prepare it, model it, and analyze the data.
194
What's the difference between an iterator and a generator?
Reference answer
An iterator is an object that implements __iter__() and __next__(), whereas a generator is a special type of iterator that is defined using a regular function and the yield keyword.
195
What is Scope Resolution in Python?
Reference answer
Sometimes objects within the same scope have the same name but function differently. In such cases, scope resolution comes into play in Python automatically. A few examples of such behavior are: - Python modules namely 'math' and 'cmath' have a lot of functions that are common to both of them - log10(), acos(), exp() etc. To resolve this ambiguity, it is necessary to prefix them with their respective module, like math.exp() and cmath.exp(). - Consider the code below, an object temp has been initialized to 10 globally and then to 20 on function call. However, the function call didn't change the value of the temp globally. Here, we can observe that Python draws a clear line between global and local variables, treating their namespaces as separate identities. temp = 10 # global-scope variable def func(): temp = 20 # local-scope variable print(temp) print(temp) # output => 10 func() # output => 20 print(temp) # output => 10 This behavior can be overridden using the global keyword inside the function, as shown in the following example: temp = 10 # global-scope variable def func(): global temp temp = 20 # local-scope variable print(temp) print(temp) # output => 10 func() # output => 20 print(temp) # output => 20
196
What are conditional statements in Python?
Reference answer
Conditional statements control the flow of execution using if, elif, and else. Example: x = 5 if x > 0: print("Positive") elif x == 0: print("Zero") else: print("Negative")
197
How would you handle missing data in a Pandas DataFrame? Write a function that takes a DataFrame and fills missing values in a specified column with the column's mean value.
Reference answer
import pandas as pd def fill_missing_values(df, column): mean_val = df[column].mean() df[column].fillna(mean_val, inplace=True) return df # Example usage # df = pd.DataFrame({'Values': [1, 2, None, 4]}) # df_filled = fill_missing_values(df, 'Values') Explanation of solution: The function fill_missing_values calculates the mean of the specified column and fills missing values with this mean. fillna is used with inplace=True to modify the original DataFrame. This is a common approach to handle NaN values in datasets.
198
How do you automate Excel tasks in Python?
Reference answer
Use openpyxl for reading/writing Excel files. Example: import openpyxl # Create a new workbook wb = openpyxl.Workbook() ws = wb.active # Write to a cell ws['A1'] = 'Hello' # Save the workbook wb.save('example.xlsx')
199
Define polymorphism in Python.
Reference answer
As the name suggests, polymorphism is the ability of a thing to assume many forms. In Python, it refers to using a function for different data types (strings, integers, booleans, or floats). While two functions will have identical names, they will differ by signatures.
200
What are Deep Copy and Shallow Copy ?
Reference answer
Shallow Copy: - Shallow copy creates a new object and then copies the references of the original object's elements into the new object. - The new object and the original object share the same elements (references), so changes made to one object may affect the other. - In a shallow copy, the top-level elements are copied, but the nested objects within them are not duplicated. - Shallow copies are created using methods like slicing, the `copy()` method, or the `copy` module. Deep Copy: - Deep copy creates a new object and recursively copies all the elements and nested objects of the original object. - The new object is completely independent of the original object, and any changes made to one object do not affect the other. - Deep copies ensure that all levels of the object hierarchy are duplicated, including nested objects and their references. - Deep copies are created using the `copy.deepcopy()` function from the `copy` module.