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

Basic Python Developer Interview Questions Explained | 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 a namespace?
Reference answer
A namespace is a naming system used to make sure that names are unique to avoid naming conflicts.
2
Describe Python's with statement and its advantage.
Reference answer
The with statement simplifies exception handling by encapsulating common preparation and cleanup tasks in context managers. It's often used for file handling to ensure files are properly closed.
Career Acceleration

Earn a certification to make your resume stand out.

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

1 100% Pass Rate
2 2 Weeks of Dump Practice
3 Pass the Certification Exam
3
What is pickling and Unpickling in Python ?
Reference answer
Pickling: - Pickling is the process of converting a Python object hierarchy into a byte stream. - It allows you to save the state of an object or a collection of objects as a file or transfer it over a network. - The resulting byte stream can be stored persistently or transmitted between different systems. - Pickling is commonly used for tasks like caching, serialization, and data persistence. Unpickling: - Unpickling is the process of reconstructing a Python object hierarchy from a byte stream. - It is the reverse operation of pickling and allows you to restore the state of the objects. - By unpickling, you can retrieve the original object or data structure that was pickled. - Unpickling is essential when you want to retrieve and utilize the saved data or objects.
4
How do you merge two DataFrames in Pandas?
Reference answer
You can merge two DataFrames using functions like `pd.concat()`, `pd.merge()`, or by using the `.append()` method.
5
What are Keywords in Python?
Reference answer
Keywords in python are reserved words that have special meaning.They are generally used to define type of variables. Keywords cannot be used for variable or function names. There are following 33 keywords in python-
6
Describe the difference between deep and shallow copy.
Reference answer
A shallow copy replicates the outer object, but not the inner objects. A deep copy replicates both the outer and inner objects, creating a fully independent clone.
7
What is Pandas?
Reference answer
Pandas is a data manipulation package in Python for tabular data. That is, data in the form of rows and columns, also known as DataFrames. Intuitively, you can think of a DataFrame as an Excel sheet. Pandas' functionality includes data transformations, like sorting rows and taking subsets, to calculating summary statistics such as the mean, reshaping DataFrames, and joining DataFrames together. pandas works well with other popular Python data science packages, often called the PyData ecosystem, including pandas is used throughout the data analysis workflow. With pandas, you can: pandas also contains functionality for time series analysis and analyzing text data.
8
Can you elaborate on how TDD contributes to code maintainability and extensibility over the long term, based on your experience?
Reference answer
TDD leads to better-designed code with clearly defined interfaces. In practice, this means that as the project evolves, it's easier to make changes without introducing regressions, leading to more maintainable and extensible codebases.
9
What is the difference between Matplotlib and Seaborn?
Reference answer
Matplotlib is a low-level plotting library in Python that provides a wide range of options for customization and control over plot elements. Seaborn is a higher-level library that builds on Matplotlib to provide more streamlined and aesthetic visualizations with less code. Seaborn also provides a range of built-in plot types and color palettes that make it easy to create attractive visualizations.
10
What happens with list = [[0]] * 3 and why is it tricky?
Reference answer
This creates three references to the same inner list, not three separate lists, so changing one row changes all rows, this looks fine when printing at first, but breaks when you try to modify one element, which is why it is a very common trap. lst = [[0]] * 3 lst[0][0] = 5 print(lst) # [[5], [5], [5]]
11
How is multithreading handled in Python, and what is the Global Interpreter Lock (GIL)?
Reference answer
Python uses the threading module for multithreading. However, due to the GIL in CPython, only one thread executes Python bytecode at a time, limiting parallelism for CPU-bound tasks. Example: import threading def worker(): print("Thread is running") # Create a thread targeting the worker function t = threading.Thread(target=worker) # Start the thread t.start() # Wait for the thread to finish t.join() The GIL is ideal for I/O-bound tasks, but it can create a performance bottleneck for CPU-bound tasks.
12
How would you sort a dictionary in Python?
Reference answer
You use the sorted() function to sort a dictionary in Python (dictionaries are unordered data structures that map keys to values). The method takes in three parameters: object (required), as well as key and reverse (both optional). The sorted() function in Python is not just useful for dictionaries but can be used to sort any iterable objects by a key, such as lists and tuples.
13
Write a Python function to count the number of vowels in a string.
Reference answer
Solution: def count_vowels(s): # Define vowels vowels = "aeiouAEIOU" # Initialize count count = 0 # Count vowels for char in s: if char in vowels: count += 1 return count # Example usage input_string = "Hello, World!" vowel_count = count_vowels(input_string) print("Number of vowels in the string:", vowel_count) Output: Number of vowels in the string:3
14
How do you ensure code quality in a team environment?
Reference answer
Through code reviews, adhering to coding standards (PEP 8), using linters (e.g., pylint), and writing unit tests.
15
How does Python handle memory management through reference counting and garbage collection?
Reference answer
Python handles memory automatically through reference counting and garbage collection. Objects are deallocated when their reference count drops to zero. However, while the del statement removes a reference, it doesn't guarantee immediate memory release - garbage collection handles that, especially for cyclic references that reference counting alone can't resolve.
16
Explain the concept of a dictionary in Python.
Reference answer
A dictionary is an unordered collection of key-value pairs in Python. # Creating a dictionary student = { 'name': 'Alice', 'age': 25, 'grade': 'A', 'courses': ['Math', 'History', 'Science'] } # Accessing values by keys print("Name:", student['name']) print("Age:", student['age']) print("Courses:", student['courses']) # Modifying values student['age'] = 26 student['grade'] = 'B' # Printing the modified dictionary print("\nModified Dictionary:") for key, value in student.items(): print(f"{key}: {value}") Expected Output: Name: Alice Age: 25 Courses: ['Math', 'History', 'Science'] Modified Dictionary: name: Alice age: 26 grade: B courses: ['Math', 'History', 'Science']
17
How to copy an object in Python?
Reference answer
Objects in Python can be copied using the copy module. The copy.copy() function performs a shallow copy, while copy.deepcopy() performs a deep copy. Alternatively, slicing or the list() constructor can copy sequences shallowly.
18
Write a program to sort a list of numbers.
Reference answer
Sample Answer: Sorting a list can be easily done using Python's built-in sorted() function. For example: def sort_numbers(numbers): return sorted(numbers)
19
How can you find the hostname of an IP address in Python?
Reference answer
we can use the gethostbyaddr function from the socket module to look up the hostname of the given IP address.
20
Write a Python function to calculate the sum of digits of a number.
Reference answer
Solution: def sum_of_digits(number): # Convert number to string to iterate through its digits num_str = str(number) # Initialize sum digit_sum = 0 # Iterate through each digit and add it to the sum for digit in num_str: digit_sum += int(digit) return digit_sum # Example usage input_number = 12345 result = sum_of_digits(input_number) print("Sum of digits in", input_number, "is", result) Output: Sum of digits in 12345 is 15
21
How to identify elements which are not common in both Series?
Reference answer
The below program is to identify the elements which are not common in both series: import pandas as pd import numpy as np sr1 = pd.Series([1, 2, 3, 4, 5]) sr2 = pd.Series([2, 4, 6, 8, 10]) print("Original Series:") print("sr1:") print(sr1) print("sr2:") print(sr2) print("nItems of a given series not present in another given series:") sr11 = pd.Series(np.union1d(sr1, sr2)) sr22 = pd.Series(np.intersect1d(sr1, sr2)) result = sr11[~sr11.isin(sr22)] print(result)
22
Describe a situation where you optimized a piece of code for better performance.
Reference answer
Provide an example where the candidate identified bottlenecks using profiling tools and implemented optimizations, such as algorithmic improvements or memory management techniques.
23
What is PEP 8 and why is it important in Python?
Reference answer
PEP 8 is the official Style Guide for Python Code, established as a Python Enhancement Proposal. It defines conventions for formatting and structuring Python code to maximize readability, consistency, and maintainability across the global Python ecosystem. Key guidelines include: using 4 spaces per indentation level, limiting lines to 79 characters, using two blank lines around top-level functions and classes, using CapWords (PascalCase) for classes, snake_case for functions and variables, and UPPER_CASE for constants. PEP 8 prioritizes readability and consistency, following the philosophy that 'code is read much more often than it is written.'
24
How can you generate random numbers?
Reference answer
Python provides a module called random using which we can generate random numbers. - We have to import a random module and call the random() method as shown below: - The random() method generates float values lying between 0 and 1 randomly. import random print(random.random()) - To generate customised random numbers between specified ranges, we can use the randrange() method Syntax: randrange(beginning, end, step) For example: import random print(random.randrange(5,100,2))
25
What is "The Zen of Python"?
Reference answer
It is the principle that influences the design of Python programming.
26
The following code is supposed to create a list of the first five even numbers. What is wrong with the code, and how can it be fixed? even_numbers = [0, 2, 4, 6, 8]
Reference answer
The code is correct.
27
How can you split a string in Python?
Reference answer
The split() method is used to separate a given String in Python. Example: a="edureka python" print(a.split()) Output: [‘edureka', ‘python']
28
What are coroutines in Python, and how can they be utilized?
Reference answer
Coroutines are a type of function that may delay its execution and resume it later, so they can be used for asynchronous programming. Use async def to define a coroutine and use await to pause execution. Example: import asyncio async def greet(): await asyncio.sleep(1) print("Hello") # Run the asynchronous function asyncio.run(greet())
29
Write a Python function to filter the data to include only records from a specified region and date range. The function should return a DataFrame containing the filtered data.
Reference answer
def filter_and_aggregate_revenue(df, start_date, end_date, region): filtered_df = df[(df['Date'] >= start_date) & (df['Date'] <= end_date) & (df['Region'] == region)] revenue_by_product = filtered_df.groupby('Product')['Revenue'].sum().reset_index() return revenue_by_product
30
What tools and libraries assist in debugging memory management issues in Python?
Reference answer
Tools and libraries include objgraph for visualizing object graphs, tracemalloc for tracking memory blocks, heapy from the guppy package, memory_profiler for function-level tracking, and valgrind for lower-level inspection where integration is possible.
31
How can you return a range of characters of a string?
Reference answer
You can return a range of characters by using the "slice syntax". Specify the start index and the end index, separated by a colon, to return a part of the string, for example: Get the characters from position 2 to position 5 (not included): b = "Hello, World!" print(b[2:5])
32
How does break, continue, and pass work?
Reference answer
break terminates the current loop prematurely, continue skips the rest of the current iteration and moves to the next one, and pass does nothing and acts as a placeholder. These are used in loops and conditionals to control flow.
33
Write a Program to solve the given equation assuming that a,b,c,m,n,o are constants: ax + by = c, mx + ny = o
Reference answer
By solving the equation, we get: a, b, c, m, n, o = 5, 9, 4, 7, 9, 4 temp = a*n - b*m if n != 0: x = (c*n - b*o) / temp y = (a*o - m*c) / temp print(str(x), str(y))
34
What rules govern local and global variables in Python?
Reference answer
In Python, variables are used for labeling and storing data. There are mainly two types of variables in Python - local and global. When a variable is not defined within a function, therefore is referenced within that function, its scope is global and it is called a global variable. When a variable is defined within a function, its scope is local and it is called a local variable. Additionally, using the keyword, ‘global', you can explicitly declare a variable, declared within a function, as a global variable. Since the local variable is defined within a function, when accessed outside that function, it will return an error. Global variables, on the other hand, can be accessed throughout the program.
35
53. Can you explain the purpose and usage of Django?
Reference answer
The purpose of Django is to facilitate rapid web development by providing a high-level framework written in Python. Django can be used to build almost any type of website from content management systems and wikis, through to social networks and news sites. Django follows the "batteries-included" philosophy, offering tools and libraries needed for most web development tasks within the framework itself. It includes an ORM (Object-Relational Mapping) for database interactions, a routing system for URLs, and built-in security features to prevent common web attacks like cross-site scripting and SQL injection. Developers use Django because it streamlines the process of creating robust, scalable, and maintainable web applications.It promotes code reusability and efficiency, by adhering to the DRY (Don't Repeat Yourself) principle. Developers can focus on application logic rather than boilerplate code, with its admin interface, database schema migrations, and templating system.
36
Explain list comprehensions in Python with examples.
Reference answer
List comprehensions are a concise way to create lists in Python. They allow you to generate a new list by specifying the expression and an optional filter condition. Here's an example: # Create a list of squares of numbers from 1 to 5 squares = [x**2 for x in range(1, 6)] print(squares) # Output: [1, 4, 9, 16, 25]
37
9. How are errors and exceptions handled in Python?
Reference answer
Errors and exceptions in Python are handled using the try/except/finally statement. This statement allows you to wrap code to raise an exception in a try block. The execution of the try block is stopped and the code in the except block is executed, If an exception is raised. The except block is used to handle specific types of exceptions, or all exceptions in general. The try-except block is the primary way to catch and handle exceptions. You enclose the potentially error-prone code in a try block. The code inside the corresponding except block executes, If an exception arises in the try block. The exception can decide whether to stop the program or continue with alternate logic. Python also has the finally clause. This block of code always executes, irrespective of whether an exception occurred in the try block. It's useful for cleanup actions, such as closing a file or releasing resources. Raising exceptions is another aspect. Exceptions are triggered using the raise keyword. This is handy when you want to enforce specific conditions in your code. Your engineers should not be hiring. They should be coding. Help your team focus on what they were hired for. Flexiple will manage your entire hiring process and scale your tech team.
38
Explain how to perform merge and join operations between two DataFrames in Pandas. Provide an example function that takes two DataFrames and a key column, and returns a merged DataFrame based on that key.
Reference answer
import pandas as pd def merge_dataframes(df1, df2, key_column): return pd.merge(df1, df2, on=key_column) # Example usage # df1 = pd.DataFrame({'Key': ['A', 'B', 'C'], 'Data1': [1, 2, 3]}) # df2 = pd.DataFrame({'Key': ['B', 'C', 'D'], 'Data2': [4, 5, 6]}) # merged_df = merge_dataframes(df1, df2, 'Key') Explanation of solution: The function merge_dataframes demonstrates how to merge two DataFrames using a common key column. pd.merge is a versatile function in Pandas for database-style joining of DataFrames. The example shows an inner join, but other join types (left, right, outer) can be specified with the how parameter.
39
Explain how you can profile the performance of a Python application and identify bottlenecks.
Reference answer
Python offers various profiling tools, including the built-in `cProfile` module, which helps analyze code execution times``.
40
What is the purpose of the async and await keywords in Python, and how are they used in asynchronous programming?
Reference answer
` ```async``` ` defines a coroutine, and ` ```await``` ` is used to pause the execution of a coroutine until an awaited task is complete, enabling asynchronous programming.
41
22. What is the difference between a function and a method in Python?
Reference answer
The difference between a function and a method in Python is that functions are independent blocks of code that can be called from anywhere and methods are objects or classes and need an object or class instance to be invoked. A function is a block of code that performs a specific task and can be defined using the `def` keyword. It's a standalone entity and does not depend on any object. Functions take inputs, known as parameters, and return a value. They are essential for code modularity and reusability. A method is a function associated with an object. Method operates on data that belongs to the object and is defined within a class. You need to reference it with an object, when you call a method. For example, in the expression `obj.method()` , `method` is a method of the object `obj` . Methods have at least one parameter by default, typically named `self` , which refers to the object on which the method is called. Both functions and methods represent blocks of code in Python, methods are bound to objects, whereas functions are not.
42
Write a Python function to remove duplicate characters from a string.
Reference answer
Solution: def remove_duplicates(input_string): # Initialize an empty set to store unique characters unique_chars = set() # Initialize an empty string to store the result result = "" # Iterate through each character in the input string for char in input_string: # Add the character to the result string if it's not already in the set if char not in unique_chars: result += char unique_chars.add(char) return result # Example usage input_string = "hello world" result = remove_duplicates(input_string) print("String with duplicates removed:", result) Output: String with duplicates removed: helo wrd
43
What is a lambda function?
Reference answer
A lambda function is an anonymous function. This function can have any number of parameters but, can have just one statement. In the example, we defined a lambda function(upper) to convert a string to its upper case using upper(). s1 = 'GeeksforGeeks' s2 = lambda func: func.upper() print(s2(s1)) Output GEEKSFORGEEKS
44
What is the purpose of generators in Python, and how are they different from regular functions?
Reference answer
Generators are functions that yield values one at a time, enabling efficient memory usage. They save and resume state between calls.
45
What is the purpose of the super() function in Python?
Reference answer
The super() function is used to call a method from the parent class. It is commonly used in the __init__ method of a derived class to ensure that the initialization of the parent class is also performed. class ChildClass(ParentClass): def __init__(self, x, y): super().__init__(x) self.y = y
46
What is a set in Python, and what makes it different from a list?
Reference answer
A set is an unordered collection of unique elements in Python. It does not allow duplicate elements. Unlike lists, sets do not have an order, and indexing is not supported. my_set = {1, 2, 3, 4, 5}
47
Write Python code to print the length of each line in a particular file, not counting whitespace at the ends.
Reference answer
with open('filename.txt', 'r') as file: print(len(file.readline().rstrip()))
48
Explain the purpose of the with statement in Python.
Reference answer
The with statement is used for context management and ensures proper resource cleanup (e.g., file closure) when exiting the block. It is often used with file handling, database connections, and more.
49
How is memory profiling conducted to identify and solve memory leaks in Python applications?
Reference answer
Memory profiling is conducted using tools such as memory_profiler, objgraph, and tracemalloc to monitor memory usage, detect leaks, and track allocation patterns. Developers analyze memory snapshots to locate unreferenced or unexpectedly retained objects.
50
Define GIL.
Reference answer
GIL stands for Global Interpreter Lock. This is a mutex used for limiting access to python objects and aids in effective thread synchronization by avoiding deadlocks. GIL helps in achieving multitasking (and not parallel computing). The following diagram represents how GIL works. Based on the above diagram, there are three threads. First Thread acquires the GIL first and starts the I/O execution. When the I/O operations are done, thread 1 releases the acquired GIL which is then taken up by the second thread. The process repeats and the GIL are used by different threads alternatively until the threads have completed their execution. The threads not having the GIL lock goes into the waiting state and resumes execution only when it acquires the lock.
51
What is a lambda function?
Reference answer
An anonymous function is known as a lambda function. This function can have any number of parameters but, can have just one statement. Example: a = lambda x,y : x+y print(a(5, 6)) Output: 11
52
Using Django REST Framework, create a serializer for the Book model. Then, write a view to handle a GET request that returns a JSON response containing all books using this serializer.
Reference answer
# serializers.py from rest_framework import serializers from .models import Book class BookSerializer(serializers.ModelSerializer): class Meta: model = Book fields = ['title', 'author', 'publication_date'] # views.py from rest_framework.views import APIView from rest_framework.response import Response from .models import Book from .serializers import BookSerializer class BookList(APIView): def get(self, request, format=None): books = Book.objects.all() serializer = BookSerializer(books, many=True) return Response(serializer.data) # urls.py from django.urls import path from .views import BookList urlpatterns = [ # ... other url patterns ... path('api/books/', BookList.as_view(), name='api_book_list'), ] Explanation of solution: A BookSerializer class is defined using Django REST Framework's serializers.ModelSerializer. It specifies the model to serialize and the fields to include. A class-based view BookList is created, using APIView from Django REST Framework. It handles GET requests and returns a JSON response containing serialized data of all books. The corresponding URL pattern is added to urls.py, pointing to the BookList view for the route 'api/books/'.
53
What are the differences between the os.path and pathlib modules in Python for file and directory manipulation?
Reference answer
`os.path` provides functions for working with paths as strings, while `pathlib` introduces an object``-oriented approach for path manipulation.
54
13. What is the difference between deep and shallow copy?
Reference answer
The difference between deep and shallow copy is that in Shallow copy, a copy of the original object is stored and only the reference address is finally copied. In Deep copy, the copy of the original object and the repetitive copies both are stored. The difference between a shallow copy and a deep copy is that a shallow copy only copies the reference to the original object, while a deep copy copies all of the object's properties, including any nested objects. Objects can contain references to other objects.The manner in which these internal references are handled defines whether the copy is deep or shallow in Python. A shallow copy creates a new object, but does not create copies of the objects that the original object references. The new object maintains references to the same objects as the original. This means changes to nested objects inside the copied object reflect in the original, and vice versa. A deep copy, on the other hand, creates a new object and also recursively copies all the objects referenced by the original object. This results in a true duplication, where the original and its copy are entirely independent. Changes to nested objects inside the copied object do not affect the original, and vice versa. The `copy ` module in Python provides functions for both types of copies. Use `copy()` for shallow copying and `deepcopy() ` for deep copying.
55
How does Python's exception handling work?
Reference answer
Python uses a structured mechanism with four primary blocks: try (contains code that might raise an exception), except (executes if an exception occurs; specific exceptions should be caught), else (executes only if try completes without exceptions), and finally (executes regardless of outcome, used for resource cleanup). Python 3.11+ introduced Exception Groups (ExceptionGroup) for propagating multiple unrelated exceptions simultaneously, handled with except* syntax. The with keyword implements the Context Manager protocol for automatic resource management. The raise statement manually triggers exceptions, and implicit/explicit chaining preserves tracebacks using the from keyword. Modern Python (3.11+) allows attaching metadata to exceptions using add_note() method.
56
How can you handle data serialization and deserialization in Python?
Reference answer
Python provides the pickle module for data serialization and deserialization. Pickle allows you to convert Python objects into a byte stream (serialization) and vice versa (deserialization). Here's an example: import pickle data = {name': John', age': 30} # Serialization with open(data.pkl', wb') as file: pickle.dump(data, file) # Deserialization with open(data.pkl', rb') as file: loaded_data = pickle.load(file) print(loaded_data) # Output: {name': John', age': 30}
57
How are large datasets handled in memory-constrained environments using Python?
Reference answer
Large datasets are handled by streaming data with iterators/generators, processing data in chunks, using memory-mapped files (like numpy.memmap), leveraging out-of-core computation frameworks such as Dask, and reducing memory footprint with efficient data representations.
58
Explain the concept of first-class functions in Python?
Reference answer
In Python, functions are considered first-class citizens, which means they can be treated as objects and assigned to variables, passed as arguments to other functions, and returned from other functions. This allows for powerful functional programming paradigms, such as using higher-order functions and creating closures.
59
How do you implement memoization in Python, and why is it useful in recursive functions?
Reference answer
Memoization involves caching results to avoid redundant calculations in recursive functions, improving performance. You can use dictionaries or functools' `lru_cache` for memoization``.
60
Longest Substring Without Repeating Characters: How do you find the longest unique-character substring?
Reference answer
You use a sliding window with a set, move the right pointer adding characters, if a character repeats you move the left pointer and remove characters until it becomes unique again, and keep track of the max length seen so far. def longest_unique(s): seen = set() left = 0 max_len = 0 for right in range(len(s)): while s[right] in seen: seen.remove(s[left]) left += 1 seen.add(s[right]) max_len = max(max_len, right - left + 1) return max_len print(longest_unique("abcabcbb")) # 3
61
What is the significance of PEP 8 in Python?
Reference answer
- PEP 8 is the official style guide for writing Python code. It recommends formatting conventions for indentation, spacing, naming, and other aspects. Following PEP 8 improves code readability, maintainability, and consistency within the Python community. It avoids confusion and makes collaborating on code easier. - Python Example: # Correct (PEP 8 compliant) def my_function(): pass # Incorrect def my_function(): pass
62
What Are Python's Key Features?
Reference answer
Python is interpreted and dynamically typed. It has easy syntax and readable code. It has vast libraries (like NumPy, Pandas, Flask).
63
What is the @property in Python?
Reference answer
The @property is a decorator. In Python, decorators enable users to use the class in the same way (irrespective of the changes made to its attributes or methods). The @property decorator allows a function to be accessed like an attribute.
64
How do you create a new column in a Pandas DataFrame?
Reference answer
You can create a new column by simply assigning values to it, like `df[```'new_column'] = values``` . The`` new column will be added to the DataFrame.`
65
Is Python case sensitive?
Reference answer
Yes, Python is a case-sensitive language.
66
What is the difference between lists, tuples and sets?
Reference answer
Lists, tuples, and sets are all used to store multiple items in a single variable, but they have different properties: A list is ordered and changeable. It allows duplicate values. A tuple is ordered but unchangeable (immutable). It also allows duplicates. A set is unordered, unindexed, and contains only unique items. It is changeable, but you cannot modify individual elements by index.
67
71. How do you connect to a database using Python?
Reference answer
The common approach is to use a library, to connect to a database using Python. The choice of library depends on the type of database. For relational databases like MySQL, SQLite, or PostgreSQL, the `sqlite3`, `MySQL-connector-python`, and `psycopg2` modules, respectively, are prevalent choices. The connection is straightforward as SQLite uses a file-based system, for a SQLite database. You'd open a connection using the `sqlite3.connect()` method. You'd use the `connect()` function of the `mysql.connector` module, when dealing with MySQL. PostgreSQL connections are managed using the `psycopg2.connect()` function. Do remember to close the connection after operations, using the `close()` method, to free up resources. For more advanced database operations and ORM (Object-Relational Mapping) capabilities, you can use SQLAlchemy. This powerful library provides an abstracted way to interact with various databases and can simplify the database connection process, especially in larger applications.
68
Is everything object in Python?
Reference answer
Everything in Python is an object, and almost everything has attributes and methods. All functions have a built-in attribute __doc__, which returns the doc string defined in the function's source code. The sys module is an object which has (among other things) an attribute called path.
69
How to get the indices of N maximum values in a NumPy array?
Reference answer
We can get the indices of N maximum values in a NumPy array using the below code: import numpy as np arr = np.array([1, 3, 2, 4, 5]) print(arr.argsort()[-3:][::-1]) Output [ 4 3 1 ]
70
Is it possible to call parent class without its instance creation?
Reference answer
Yes, it is possible if the base class is instantiated by other child classes or if the base class is a static method.
71
Which python framework is best flask or django ?
Reference answer
Django provides a wide range of built-in features and components, reducing the need for external libraries or packages. - Rapid development: Django's high-level abstractions and conventions simplify the development process, allowing you to build applications quickly. - Scalability: Django has proven to be scalable and has been used successfully in handling high-traffic websites and complex applications. - Larger Community: Django has a large and active community, offering extensive documentation, tutorials, and reusable packages. - Better Security Module: Django incorporates security features by default, including protection against common vulnerabilities. Flask, on the other hand, is a lightweight micro-framework that offers more flexibility and customization options. It is suitable for smaller projects, APIs, or situations where simplicity and control are desired. Flask allows developers to have more control over the architecture and components they use but lacks some of the built-in functionalities provided by Django. Conclusion is that Django's comprehensive feature set, strong community support, and emphasis on convention-over-configuration make it a preferred choice for many web development projects.
72
Explain and give an example of vstack() in numpy?
Reference answer
vstack() in NumPy stacks arrays vertically (row-wise) to form a single array. For example, vstack([array1, array2]) combines two arrays with the same number of columns into one array with added rows.
73
Two Sum: How do you return the indices of two numbers that add up to a target?
Reference answer
The idea is to use a dictionary to remember numbers we have already seen and their index, for each number we check if the needed value to reach the target is already in the dictionary, if yes we return both indexes, this works in one pass and is much faster than checking every pair. def two_sum(nums, target): seen = {} for i, n in enumerate(nums): need = target - n if need in seen: return [seen[need], i] seen[n] = i print(two_sum([2, 7, 11, 15], 9)) # [0, 1]
74
Multiple Choice Question: What is the output of the following code? try: if '1' != 1: raise "someError" else: print("someError has not occured") except "someError": print ("someError has occured") a) someError has occured b) someError has not occured c) invalid code d) none of the above
Reference answer
Answer: c) invalid code A new exception class must inherit from a BaseException. There is no such inheritance here.
75
What are Python Modules? Name Some Popular Ones.
Reference answer
Python Modules are files containing executable Python codes. Breaking down a monolithic code into smaller units makes it modular, readable, efficient, and easier to debug. Some commonly used Python modules include: - PMW, PyGObject, wxPython, WCK, etc. – for graphical interfaces - SQLAlchemy, KInterbasDB, MySQLdb, Gadfly, etc. – for databases - Selenium, scrape, Google Maps, requests, pyquery, etc. – for web development - Python Imaging Library, MoviePy, pyscreenshot, GDmodule, VideoCapture, etc. – for image and video manipulation - pySonic, PyMedia, PMIDI, Mutagen, etc. – for sound manipulation - Numpy, SciPy, Pandas, Matplotlib, etc. – for data science and mathematical computations - Pygame, pyOpenGL, Pyglet, etc. – for game development
76
Write a function to check if a given string is a valid palindrome considering only alphanumeric characters.
Reference answer
Sample Answer: To check if a string is a valid palindrome while ignoring non-alphanumeric characters, you can clean the string using regular expressions and then compare it with its reverse. Here is an example of how to check if a given string is a valid palindrome considering only alphanumeric characters: import re def is_valid_palindrome(s): s = re.sub(r'[^a-zA-Z0-9]', '', s).lower() return s == s[::-1]
77
Explain how to perform data aggregation and group-by operations in Pandas.
Reference answer
- Use groupby with aggregate functions like sum, mean, count, and custom functions.
78
This code is supposed to use a lambda function to sort a list of dictionaries by the value of a specific key. Fix the code. data = [{'name': 'Alice', 'age': 28}, {'name': 'Bob', 'age': 21}, {'name': 'Charlie', 'age': 35}] sorted_data = sorted(data, key=lambda x: x['age']) print(sorted_data)
Reference answer
The code is correct and will sort the list of dictionaries by the age key.
79
How do you concatenate two matrices in NumPy?
Reference answer
You can concatenate two matrices in NumPy using the numpy.concatenate() function or the numpy.vstack() and numpy.hstack() functions for vertical and horizontal concatenation.
80
What is the purpose of a virtual environment in Python?
Reference answer
A virtual environment is used to create isolated Python environments where you can install specific packages and dependencies without affecting the global Python installation. It helps avoid conflicts between different projects that may require different versions of the same package.
81
How can you convert a given integer to an IP address in Python?
Reference answer
we can use the pack function from the struct module to convert the integer to a 32-bit packed binary format in network byte order.
82
Explain the concept of "duck typing" in Python.
Reference answer
Duck typing refers to the philosophy that what an object can do (its behavior) is more important than its actual type. If an object walks and quacks like a duck, it's treated as a duck.
83
62. Can you explain how a binary search tree works?
Reference answer
A binary search tree (BST) is a data structure where each node has, at most, two child nodes: a left child and a right child. Every node in this tree contains a distinct key, and the tree satisfies the binary search property. This means that for any given node with a key value: The values in the left subtree are less than the node's key. The values in the right subtree are greater than the node's key. You start at the root, when searching for a key in a BST. The search continues in the left subtree, If the key is less than the root's key. The search continues in the right subtree, if it's greater. This process is repeated recursively until the key is found or until the relevant subtree is empty, indicating the key isn't present in the tree. Insertions and deletions also follow a similar logic based on the key value. The efficiency of operations in a BST, like search, insert, and delete, is O(log n), if the tree is balanced. The efficiency can degrade to O(n), in the worst case, when the tree becomes skewed.
84
How do you manage dependencies for scripts?
Reference answer
Dependencies are managed using a file like requirements.txt, where you list all needed packages, others can install them easily using pip, this makes scripts easy to share and run on other machines, and avoids "it works on my system" problems. pip freeze > requirements.txt pip install -r requirements.txt
85
Write a Python program to get yesterday's, today's, and tomorrow's dates.
Reference answer
from datetime import datetime, timedelta def get_dates(): # Get today's date today = datetime.now().date() # Calculate yesterday's and tomorrow's date yesterday = today - timedelta(days=1) tomorrow = today + timedelta(days=1) return yesterday, today, tomorrow # Get the dates yesterday_date, today_date, tomorrow_date = get_dates() # Display the dates print("Yesterday's date:", yesterday_date) print("Today's date:", today_date) print("Tomorrow's date:", tomorrow_date) This program uses the datetime module to work with dates. It defines a function get_dates() to calculate yesterday's, today's, and tomorrow's dates using timedelta objects. Then, it calls this function and prints the dates accordingly.
86
What is PEP8?
Reference answer
PEP8 is the latest set of Python coding standards. It is a document that provides guidelines and best practices for how to write Python code. Its primary focus is to improve the readability and consistency of Python code.
87
Print all factors of a number:
Reference answer
def factors(n): for i in range(1, n + 1): if n % i == 0: print(i)
88
Write a Python program to calculate the factorial of a number.
Reference answer
def factorial(n): if n == 0: return 1 return n * factorial(n - 1) print(factorial(5)) # 120
89
How do you print "Hello, World!" in Python?
Reference answer
You can print "Hello, World!" using the print() function like this: print("Hello, World!")
90
72. How would you explain the concept of CRUD operations in database management?
Reference answer
The concept of CRUD operations in database management refers to the four functions of persistent storage.It's essential to understand these operations when interacting with databases using libraries like SQLAlchemy or Django ORM. CRUD stands for Create, Read, Update, and Delete. These operations define the basic tasks you can perform on stored data. Use the `INSERT` command to create data, the `SELECT` command to read data, the `UPDATE` command to modify data, and the `DELETE` command to remove data, when developing a Python application. Ensure data integrity and security when performing CRUD operations. Use prepared statements or ORM techniques, for example, to prevent SQL injection attacks.
91
Differentiate between Pyramid, Django, and Flask.
Reference answer
| Django | Pyramid | Flask | |---|---|---| | Django is a high-level, full-featured web framework that follows the batteries included methodology. | Pyramid is a flexible, minimalist web framework that follows the “pay only for what you need”. | Flask is a lightweight web framework that has simplicity and extensibility. | | It provides a huge set of built-in features, such as an ORM (Object-Relational Mapping), authentication, routing, templating, and admin interface. | It provides a core set of tools for building web applications, allowing developers to choose and add additional components as needed. | It provides the resources for building web applications but keeps the core framework minimalistic. | | Django is suitable for building complex, database-driven web applications with less code and rapid development. | Pyramid is highly customizable and adaptable, making it suitable for a wide range of applications, from simple to complex. | Flask allows developers to choose extensions based on their specific requirements, making it highly modular. | | It enforces a specific project structure and follows the Model-View-Controller (MVC) architectural pattern. | It follows a “traversal” routing system and supports various templating engines. | It follows a route-decorator approach and supports various templating engines. |
92
Write a function that takes a list and a target number, and returns the count of occurrences of the target number in the list. For instance, in the list [1, 2, 3, 2, 2, 4] and target number 2, the function should return 3. Avoid using the count function.
Reference answer
def count_occurrences(numbers, target): count = 0 for number in numbers: if number == target: count += 1 return count Explanation of solution: The function iterates over the list numbers. It uses a variable count to keep track of how many times the target number appears in the list. Each time it finds the target number, it increments count. After iterating through the list, it returns the total count of the target number's occurrences.
93
How can you reverse a string in Python?
Reference answer
You can reverse a string in Python using slicing. For example: `reversed_string = my_string[::-1]`.
94
What is the difference between Python 2 and Python 3, and which version should you use for new projects?
Reference answer
Python 2 and Python 3 have some syntax and library differences, making them incompatible. Python 3 is the recommended version for new projects, as Python 2 reached its end-of-life on January 1, 2020, and will no longer receive updates.
95
What is meta-programming in Python, and how is it used?
Reference answer
Meta-programming is writing code that can manipulate code at runtime. It is used to create generic, reusable code, or to modify the behavior of existing code dynamically.
96
Write a Program to convert date from yyyy-mm-dd format to dd-mm-yyyy format.
Reference answer
We can again use the re module to convert the date string as shown below: import re def transform_date_format(date): return re.sub(r'(\d{4})-(\d{1,2})-(\d{1,2})', '\\3-\\2-\\1', date) date_input = "2021-08-01" print(transform_date_format(date_input)) You can also use the datetime module as shown below: from datetime import datetime new_date = datetime.strptime("2021-08-01", "%Y-%m-%d").strftime("%d:%m:%Y") print(new_data)
97
What is Python?
Reference answer
Python was created and first released in 1991 by Guido van Rossum. It is a high-level, general-purpose programming language emphasizing code readability and providing easy-to-use syntax. Python interpreters are available for many operating systems. CPython, the reference implementation of Python, is open-source software and has a community-based development model, as do nearly all of its variant implementations. The non-profit Python Software Foundation manages Python and CPython. In this course, you will learn the fundamentals of Python: from basic syntax to mastering data structures, loops, and functions. You will also explore OOP concepts and objects to build robust programs.
98
How does Python integrate with cloud services?
Reference answer
Python's compatibility with cloud services is a key strength. The language's simplicity and readability make it popular for scripting and automating cloud operations. Extensive libraries facilitate seamless integration with cloud platforms like AWS, Google Cloud Platform, and Microsoft Azure. Developers often leverage SDKs provided by these platforms, such as: – AWS provides Boto3, the AWS SDK for Python, for services like Amazon S3 and Amazon EC2. – Google Cloud Platform offers the Google Cloud Client Library for Python, for services like Google Cloud Storage and Google BigQuery. – Azure Developer SDKs are available for Python, enabling access to services like Azure Cosmos DB and Azure Functions. Utilizing APIs is critical, with most cloud services exposing RESTful or gRPC APIs that can be consumed using Python's requests library or specialized libraries like grpcio. Best practices include using virtual environments, implementing proper error handling, optimizing for statelessness and scalability, leveraging cloud-native services, and following security best practices like encrypting data and using IAM roles.
99
What are decorators in Python?
Reference answer
Decorators add functionality to the current function without changing its structure. It can also accept arguments and modify these arguments.
100
How is memory managed in Python?
Reference answer
To answer this relatively straightforward question, you just need to know that Python Memory Manager allocates memory in the form of a Python private heap space. This private heap – inaccessible to the programmer – stores all Python objects. Python also has a built-in garbage collection to recycle the private heap space's unused memory.
101
What is the purpose of the .corr() method in Pandas?
Reference answer
The `.```corr```()` method is used to compute the correlation between numeric columns in a DataFrame, providing insights into the relationships between variables.
102
What is the purpose of the if __name__ == __main__;: block in Python scripts?
Reference answer
The if __name__ == __main__;: block is used to check whether the Python script is being run directly or imported as a module into another script. Code within this block will only execute when the script is run directly, not when it is imported elsewhere. It is commonly used to define script-level behavior and test functions when the script is run standalone.
103
What are Python lambdas and why are they used?
Reference answer
Python lambdas are anonymous functions. They can accept multiple arguments but only have a single expression. They are used where a function is needed temporarily and will not be needed by other code. They are also limited in their scope of capabilities compared to a full function. multiply = lambda x, y : x * y print(multiply(2, 5)) # outputs 10
104
Explain the use of the enumerate() function in Python.
Reference answer
The enumerate() function is used to iterate over a sequence while keeping track of the index of the current item. my_list = ['a', 'b', 'c'] for index, value in enumerate(my_list): print(f"Index: {index}, Value: {value}") # Output: # Index: 0, Value: a # Index: 1, Value: b # Index: 2, Value: c
105
What is the lambda function?
Reference answer
A lambda function in Python is a small, anonymous function defined with the lambda keyword. It can take any number of arguments but returns a single expression. It is typically used for short, inline operations where a full function definition is unnecessary.
106
Write a program to produce the Fibonacci series in Python.
Reference answer
def fibonacci(n): series = [ ] a, b = 0, 1 while len(series) < n: series.append(a) a, b = b, a + b return series n = int(input("Enter number of terms in the Fibonacci series: ")) fibonacci_series = fibonacci(n) print("Fibonacci series:", fibonacci_series)
107
Explain how to delete a file in Python?
Reference answer
Use command os.remove(file_name) import os os.remove("ChangedFile.csv") print("File Removed!")
108
What is PIP?
Reference answer
PIP stands for "Pip Installs Packages." It is Python's standard package manager used to install, upgrade and manage third-party libraries and dependencies from the Python Package Index (PyPI). - Used to install Python packages from PyPI. - Comes pre-installed with most modern Python distributions. - Supports installing, upgrading and uninstalling packages. - Works from the command line. Example: pip install numpy
109
What questions are asked in Technical Interview in Python Programming Language?
Reference answer
The common topics that are included in Python Technical Interview are: - Basic Syntax - DSA Based Coding - File Handling - Libraries - Supported Frameworks .etc.
110
Define PIP.
Reference answer
PIP stands for Python Installer Package. As the name indicates, it is used for installing different python modules. It is a command-line tool providing a seamless interface for installing different python modules. It searches over the internet for the package and installs them into the working directory without the need for any interaction with the user. The syntax for this is: pip install
111
Explain your experience with performance testing tools like Locust or JMeter.
Reference answer
- Answer: Highlight generating load on web applications, analyzing performance metrics like response times, using scripts to simulate user behavior, and identifying performance bottlenecks. - Example (Locust Script for Load Testing): from locust import HttpUser, task class MyUser(HttpUser): @task def load_test(self): self.client.get('/') @task def another_task(self): self.client.post('/data', json={'key': 'value'})
112
What are the major pitfalls of Python?
Reference answer
The slow overall performance of Python, its limited multiprocessing and threading capabilities are considered to be the major pitfalls of this programming language.
113
How can you check if a key exists in a dictionary in Python, and what happens when you try to access a non-existent key?
Reference answer
You can check if a key exists in a dictionary using the in keyword. For example: my_dict = {a': 1, b': 2} if c' in my_dict: print(Key c' exists.;) else: print(Key c' does not exist.;) When you try to access a non-existent key in a dictionary, Python raises a KeyError exception. To avoid this, you can use the get() method, which returns a default value if the key is not found.
114
What Is the Difference Between Lists and Tuples?
Reference answer
Tuples can not be changed, but lists can be. Tuples are more memory efficient.
115
Write a Python function to check if a sentence is a pangram.
Reference answer
Solution: import string def is_pangram(sentence): # Convert sentence to lowercase for case-insensitive comparison sentence = sentence.lower() # Create a set of unique characters in the sentence unique_chars = set(sentence) # Remove non-alphabetic characters and spaces unique_chars.discard(" ") unique_chars.difference_update(set(string.punctuation)) # Check if all letters of the alphabet are present return len(unique_chars) == 26 # Example usage input_sentence = "The quick brown fox jumps over the lazy dog" if is_pangram(input_sentence): print("The sentence is a pangram.") else: print("The sentence is not a pangram.") Output: The sentence is a pangram.
116
Binary Tree Level Order Traversal: How do you traverse a tree level-by-level (BFS)?
Reference answer
You use a queue, start by putting the root in it, then pop one node at a time and add its children, this goes level by level, this is used in many tree problems like shortest path and views. from collections import deque def level_order(root): if not root: return [] q = deque([root]) res = [] while q: node = q.popleft() res.append(node.val) if node.left: q.append(node.left) if node.right: q.append(node.right) return res
117
Explain the use of the zip() function in Python.
Reference answer
The zip() function combines two or more iterables element-wise, creating tuples. It stops when the shortest iterable is exhausted. names = ['Alice', 'Bob', 'Charlie'] ages = [25, 30, 35] zipped = zip(names, ages) # Result: [('Alice', 25), ('Bob', 30), ('Charlie', 35)]
118
What are the types of literals in Python?
Reference answer
- Numeric Literal: Numeric literals can be floating-point values, integers, or complex numbers. - Character Literal: A character literal consists of a single character enclosed in double quotes. - Boolean Literal: The boolean literals are True or False. - Literal Collections: There are four types of literal collections, including list literals, tuple literals, set literals, and dictionary literals. - String Literal: String literal is created by assigning text to a variable using single or double quotes. Multiline literals can be formed by enclosing text within triple quotes.
119
What is Type Conversion in Python?
Reference answer
This is the conversion of one data from one type to another.
120
What are the data types in Python?
Reference answer
Variables can be used to store data of different types. Python has the following data types built-in by default, in these categories: Text Type: str Numeric Types: int, float, complex Sequence Types: list, tuple, range Mapping Type: dict Set Types: set, frozenset Boolean Type: bool Binary Types: bytes, bytearray, memoryview None Type: NoneType You can get the data type of any object by using the type() function.
121
When working on machine learning projects, how do you approach model evaluation and selection, and do you have experience with techniques like cross-validation?
Reference answer
In machine learning, we use techniques like k-fold cross-validation to assess model performance. This helps in selecting the most suitable model and avoiding overfitting. It's an essential step in ensuring the model's generalization ability.
122
How do you write a docstring in Python?
Reference answer
- Triple-quoted strings used to document functions, explaining their purpose, arguments, and return values.
123
How is Python used in the Internet of Things (IoT)?
Reference answer
Python's role in IoT is significant due to its simplicity and readability. It is widely used for scripting, automation, data analysis, and machine learning in IoT. Key advantages include its extensive library ecosystem. Libraries like GPIO Zero and RPi.GPIO are pivotal for interacting with Raspberry Pi hardware. For microcontrollers like Arduino, PySerial can be used for serial communication for sensor data collection. Python is also a go-to language for back-end development. Frameworks like Flask and Django are used to create APIs for IoT devices to communicate with back-end servers for remote device management and data aggregation. Python's data analysis capabilities with libraries like Pandas, NumPy, and Matplotlib allow processing and visualizing IoT data for insights. Machine learning libraries like TensorFlow and Scikit-learn are used to build predictive models for tasks like forecasting device failures. For security, libraries like PyCryptodome enable encryption and secure data transmission between IoT devices. Python allows for rapid prototyping and testing of IoT concepts, with fewer lines of code needed to achieve functionality, speeding up development and reducing time to market.
124
Write a Python function to reverse a string.
Reference answer
Solution: With Indexing: def reverse_string(s): return s[::-1] # Example usage input_string = "Hello, World!" reversed_string = reverse_string(input_string) print("Original string:", input_string) print("Reversed string:", reversed_string) Output: Original string: Hello, World! Reversed string: !dlroW ,olleH Without Indexing: def reverse_string(s): reversed_str = "" for char in s: reversed_str = char + reversed_str return reversed_str # Example usage input_string = "Hello, World!" reversed_string = reverse_string(input_string) print("Original string:", input_string) print("Reversed string:", reversed_string) Output: Original string: Hello, World! Reversed string: !dlroW ,olleH
125
24. What is the map function, and how is it different from list comprehension?
Reference answer
Map function works as an iterator which returns a result after applying a function to each element of the iterable. List comprehension also works similarly but it includes conditional expressions. List comprehension returns a list, whereas the map function returns an object of Iterable. List comprehension execution is faster than that of map function when the formula expression is huge and complex. Both map and list comprehension can be used for similar tasks but they differ in their approach. The map function focuses on applying a function to every element, while list comprehension can apply more complex logic and conditions. You choose a map for straightforward transformations, and list comprehension when filtering or applying conditions.
126
75. What is the purpose of ORM in Python?
Reference answer
The purpose of ORM in Python is to bridge the gap between relational databases and object-oriented programming. Developers can interact with databases using Python objects instead of writing raw SQL queries. This results in cleaner, more maintainable code. ORM provides an abstraction layer, allowing developers to change the underlying database system with minimal code adjustments. ORM enhances security by reducing the risk of SQL injection attacks, since developers are not manually constructing query strings. ORM simplifies database operations in Python applications, making them more efficient and secure.
127
What is Flask or Dash used for?
Reference answer
Flask is a web framework used for creating web applications. Dash is used to create analytical web applications and is especially helpful for data visualization. Example (Flask): from flask import Flask app = Flask(__name__) @app.route('/') def home(): return "Hello, Flask!" if __name__ == '__main__': app.run(debug=True)
128
How do you remove duplicates from a list?
Reference answer
Sample Answer: Removing duplicates from a list is a common task in data manipulation. One efficient way to achieve this is by converting the list to a set, as the sets automatically eliminate duplicate values. After removing duplicates, you can convert the set back to a list if needed. Here's how you can implement this approach: def remove_duplicates(lst): return list(set(lst))
129
How to add a new column to an existing dataframe in Pandas?
Reference answer
To add a new column to an existing dataframe, we can do that using Dataframe.insert(). The below code is an example of adding a column to an existing dataframe: import pandas as pd # Define a dictionary containing Students data data = {'Name': ['John', 'Sam', 'Michel', 'Adam','Justin'], 'Age': [24, 22, 25, 24, 26], 'Qualification': ['BE', 'MBA', 'Msc', 'Msc','MBA']} # Convert the dictionary into DataFrame df = pd.DataFrame(data) print(df) # Using DataFrame.insert() to add a column df.insert(2, "GPA", [4, 3.8, 3, 3.5, 3.6], True) print('nDataframe after insertionn') # Observe the result print(df)
130
What are generators in Python?
Reference answer
Functions that return an iterable set of items are called generators.
131
What is a Python decorator, and how is it used?
Reference answer
A decorator is a function that wraps another function and adds additional behavior to it. It is commonly used for tasks like logging, authentication, and access control.
132
Write a Python program that finds the intersection of two sets.
Reference answer
def intersection(set1, set2): return set1 & set2 print(intersection({1, 2, 3}, {2, 3, 4})) # {2, 3}
133
What are Decorators in Python?
Reference answer
Decorator is a very useful tool in Python that is used by programmers to alter the changes in the behavior of classes and functions.
134
What are Some Fundamental Features of Python?
Reference answer
Some key features are: - Open-Source: Python is free to download, and since the source code is publicly available developers can also share it at no cost. - Easy to Learn and Read: It is a developer-friendly language that follows a simple syntax, which makes it easy to learn, read, and code. - Interpreted: Python executes line-by-line, as such, there is no need to compile it. - Object-Oriented: Python is an Object Oriented Programming language. Inheritance, Class, Object, Polymorphism, and encapsulation in Python make it different from the functional programming language. - High-Level: Python Developers do not have to remember the system architecture or manage the memory. - Portable: It is a highly portable language as it is platform-independent. - Integrated: It is possible to integrate Python with other languages like C, C++, etc.
135
What Would You Say Are the Most Common Mistakes Made Using Python?
Reference answer
There are such mistakes as: - Misusing expressions as defaults for function arguments - Incorrect usage of class variables - Incorrect parameter specification for an exception block - Forgotten colon at the end of structural sentences - Inconsistency with parentheses or brackets - Not using the class name while modifying class variable values However, it may be individual to every developer. The main goal of such interview questions on Python is to identify how much experience one had in learning and fixing their own mistakes.
136
What Are Namespaces in Python?
Reference answer
A namespace is a symbolic name for an object with information about the object itself.
137
What is the in operator used for?
Reference answer
- in Operator: - Checks if an element exists in a sequence (list, tuple, string).
138
What are iterators in Python?
Reference answer
Iterators are objects which can be traversed though or iterated upon.
139
Explain how to handle dynamic web elements that change their attributes or IDs.
Reference answer
- Use WebDriverWait with ExpectedConditions to wait for elements to become visible or clickable. - Consider using relative locators or XPath constructs that adapt to dynamic changes.
140
How to install Python on Windows and set path variable?
Reference answer
To install Python on Windows, follow the below steps:
141
What is Python's range() function?
Reference answer
The range() function generates a sequence of numbers. Example: for i in range(5): print(i) # Output: 0, 1, 2, 3, 4
142
How do you open and close files in Python?
Reference answer
You can use the `open()` function to open files and the `close()` method to close them. It is recommended to use the `with` statement to ensure files are properly closed.
143
How do you merge two sorted lists into one sorted list?
Reference answer
Concatenate the lists and use the sorted() function: a = [1, 3, 5] b = [2, 4, 6] merged = sorted(a + b) print(merged) # Output: [1, 2, 3, 4, 5, 6]
144
Most Frequent Word in a Large File: How do you find the most frequent word in a memory-safe way?
Reference answer
You read the file line by line instead of loading all at once, update a counter for each word, and keep track of the current most frequent word, this avoids memory issues for big files. from collections import defaultdict def most_frequent(file_path): count = defaultdict(int) max_word = "" max_count = 0 with open(file_path) as f: for line in f: for word in line.split(): count[word] += 1 if count[word] > max_count: max_count = count[word] max_word = word return max_word
145
What are *args and **kwargs?
Reference answer
- *args: The special syntax *args in function definitions is used to pass a variable number of arguments to a function. Python program to illustrate *args for a variable number of arguments: def fun(*argv): for arg in argv: print(arg) fun('Hello', 'Welcome', 'to', 'GeeksforGeeks') Output Hello Welcome to GeeksforGeeks - **kwargs: This syntax in function definitions is used to accept a variable number of keyword arguments. These arguments are collected into a dictionary, where the keys are the argument names and the values are the corresponding values. For example: def fun(**kwargs): for k, val in kwargs.items(): print("%s == %s" % (k, val)) # Driver code fun(s1='Geeks', s2='for', s3='Geeks') Output s1 == Geeks s2 == for s3 == Geeks
146
What is the difference between sys.argv and argparse?
Reference answer
sys.argv is very basic and just gives raw arguments as a list, while argparse is a full tool to define options, flags, help messages, and validation, sys.argv is fine for small scripts, but for real tools used by others, argparse is better because it shows proper usage and errors, so in production scripts people usually prefer argparse. import argparse parser = argparse.ArgumentParser() parser.add_argument("--name") args = parser.parse_args() print("Hello", args.name) Run like: python app.py --name Aakash
147
What is the purpose of the pass statement in Python?
Reference answer
The pass statement is used as a placeholder when a statement is required syntactically, but no code needs to be executed.
148
Given an integer n, return the number of trailing zeroes in n factorial n!
Reference answer
To pass this challenge, you have to first calculate n factorial (n!) and then calculate the number of training zeros. Finding factorial In the first step, we will use a while loop to iterate over the n factorial and stop when the n is equal to 1. Calculating trailing zeros In the second step, we will calculate the trailing zero, not the total number of zeros. There is a huge difference. 7! = 5040 The seven factorials have a total of two zeros and only one trailing zero, so our solution should return 1. - Convert the factorial number to a string. - Read it back and apply for a loop. - If the number is 0, add +1 to the result, otherwise break the loop. - Returns the result. The solution is elegant but requires attention to detail. def factorial_trailing_zeros(n): fact = n while n > 1: fact *= n - 1 n -= 1 result = 0 for i in str(fact)[::-1]: if i == "0": result += 1 else: break return result factorial_trailing_zeros(10) # 2 factorial_trailing_zeros(18) # 3
149
What is the Global Interpreter Lock (GIL)?
Reference answer
The GIL is a mechanism in Python that ensures that only one thread at a time can execute Python bytecode. This can limit the performance of threaded programs, but it is necessary for ensuring the integrity of Python's memory management.
150
How can you handle missing data (NaN) in a DataFrame using Pandas?
Reference answer
You can handle missing data using methods like `.dropna()`, `.fillna()`, or `.interpolate()`, depending on your specific needs.
151
What are the best practices for memory management in Python applications processing large datasets?
Reference answer
Best practices include utilizing generators and iterators to avoid loading entire datasets into memory, leveraging built-in modules such as gc to control garbage collection, using memory profilers to identify leaks, and preferring in-place operations over creating new objects.
152
How can you replace string space with a given character in Python?
Reference answer
It is a simple string manipulation challenge. You have to replace the space with a specific character. - Example 1: A user has provided the string l vey u and the character o, and the output will be loveyou. - Example 2: A user has provided the string D t C mpBl ckFrid yS le and the character a, and the output will be DataCampBlackFridaySale. The simplest way is to use the built-in str.replace() method to directly replace spaces with the given character. def str_replace(text, ch): return text.replace(" ", ch) text = "D t C mpBl ckFrid yS le" ch = "a" str_replace(text, ch) # 'DataCampBlackFridaySale'
153
43. How to write a Python program to find the frequency of words in a string?
Reference answer
To write a Python program that finds the frequency of words in a string, utilize the built-in split method and a dictionary. Start by splitting the string into individual words using the `split()` method. This provides a list of words. Next, iterate over each word in the list. Update its count in a dictionary, for every word encountered. Add the word with a count of one,If the word is not already in the dictionary. Increment its count by one, If it exists. The dictionary will contain each unique word as a key and its frequency as the corresponding value, by the end of the iteration. This approach offers a straightforward way to analyze the word distribution in a given string.
154
Write a program to check and return the pairs of a given array A whose sum value is equal to a target value N.
Reference answer
This can be done easily by using the phenomenon of hashing. We can use a hash map to check for the current value of the array, x. If the map has the value of (N-x), then there is our pair. def print_pairs(arr, N): # hash set hash_set = set() for i in range(0, len(arr)): val = N-arr[i] if (val in hash_set): #check if N-x is there in set, print the pair print("Pairs " + str(arr[i]) + ", " + str(val)) hash_set.add(arr[i]) # driver code arr = [1, 2, 40, 3, 9, 4] N = 3 print_pairs(arr, N)
155
Have you worked with any Python web frameworks like Django or Flask? Can you discuss a challenging problem you encountered and how you solved it?
Reference answer
In a Django project, we faced scalability issues due to database bottlenecks. We resolved it by implementing database sharding and optimizing query performance.
156
26. How can you share global variables across modules?
Reference answer
Global variables are be shared across modules in Python by utilizing a dedicated module to store them. Create a module, often named `config` or `globals` , to hold these variables. They import the dedicated module, when other modules need access to these shared variables. For example, You can access the variable x in another module using `config.x` after importing `config` , if you have a variable `x` in the `config` module. It's essential to exercise caution when working with global variables, as they can make code harder to debug and maintain. Ensure clear documentation and consistent naming conventions, so developers understand their purpose and modifications don't introduce unexpected behaviors.
157
What is Python's type() function?
Reference answer
The type() function returns the data type of an object. Example: print(type(5)) # Output: print(type("hello")) # Output:
158
How can you work with threads in Python, and what are some common challenges and best practices when dealing with multi-threading?
Reference answer
Python's `threading` module allows you to create and manage threads. Common challenges include thread safety and avoiding race conditions. Best practices include using locks and synchronization mechanisms.*
159
What is the difference between the assert statement and the raise keyword in Python?
Reference answer
The assert statement in Python is used to check if a condition is true and raise an AssertionError if it is false. The raise keyword, on the other hand, is used to manually raise an exception. The assert statement is typically used for debugging purposes, while the raise keyword is used for error handling.
160
Have you worked with asynchronous programming in Python, and can you explain when and how you would use it?
Reference answer
Yes, I've used asyncio to handle concurrent I/O operations. For example, in a web application, I used it for handling multiple requests simultaneously without blocking the event loop.
161
Write a Program to add two integers >0 without using the plus operator.
Reference answer
We can use bitwise operators to achieve this. def add_nums(num1, num2): while num2 != 0: data = num1 & num2 num1 = num1 ^ num2 num2 = data << 1 return num1 print(add_nums(2, 10))
162
How do you use a dictionary in Python?
Reference answer
An unordered set of key-value pairs is called a dictionary. Example: my_dict = {'a': 1, 'b': 2} my_dict['c'] = 3 print(my_dict) # {'a': 1, 'b': 2, 'c': 3}
163
Reverse a string in Python
Reference answer
Let's reverse the string "Python" using the slicing method. To reverse a string, we simply create a slice that starts with the length of the string, and ends at index 0. To reverse a string using slicing, write: stringname[stringlength::-1] # method 1 Or write without specifying the length of the string: stringname[::-1] # method2 The slice statement means start at string length, end at position 0, move with the step -1 (or one step backward). str="Python" # initial string stringlength=len(str) # calculate length of the list slicedString=str[stringlength::-1] # slicing print (slicedString) # print the reversed string Output: nohtyP This is just one method to reverse a string in Python. Other two notable methods are Loop and Use Join.
164
Why do developers prefer NumPy arrays over Python lists?
Reference answer
Python lists have undeniable benefits when it comes to operations like concatenation, appending, item deletion, or insertion. However, their functionality is limited – there's no support for the multiplication or addition of vector values. Also, since lists support different data types, Python has to store type information for each object on the list. Thus, the execution of the code is slower. NumPy arrays are more convenient since they support both matrix and vector operations. Other operations include convolution, quick search, linear algebra, histograms, and more. Last but not least, a NumPy array is much faster than a Python list.
165
What are dataframes?
Reference answer
Dataframes are two-dimensional, labeled data structures in Python, primarily provided by the pandas library. They allow for efficient data manipulation, cleaning, and analysis, similar to a spreadsheet or SQL table.
166
Check if a number is even or odd:
Reference answer
def is_even(n): return n % 2 == 0
167
Why use NumPy arrays instead of lists in Python?
Reference answer
We use python numpy array instead of a list because of the below three reasons:
168
Explain Break, Continue, and Pass statements in Python.
Reference answer
Break - Allows loop termination when some condition is met and the control is transferred to the next statement. Continue - Allows skipping some part of a loop when some specific condition is met and the control is transferred to the beginning of the loop Pass - Used when you need some block of code syntactically, but you want to skip its execution. This is basically a null operation. Nothing happens when this is executed.
169
How do you join a list of strings into a single string?
Reference answer
To merge a list of strings, use the join() method and supply a separator (such a space): words = ['Hello', 'World'] sentence = ' '.join(words) print(sentence) # Output: 'Hello World'
170
What is an interpreted language?
Reference answer
An interpreted language is any programming language which is not in machine-level code before runtime. Therefore, Python is an interpreted language.
171
How can you profile and optimize the performance of a Python application?
Reference answer
Profiling tools like `cProfile` help identify bottlenecks. Optimization can include algorithmic improvements, caching, and using built-in functions``.
172
What is the purpose of Python's asyncio module?
Reference answer
asyncio provides tools for asynchronous programming, enabling non-blocking execution of I/O-bound tasks. It uses event loops to manage coroutines. Example: import asyncio async def say_hello(): await asyncio.sleep(1) print("Hello!") asyncio.run(say_hello())
173
How do you group anagrams from a list of strings?
Reference answer
Use a dictionary with sorted words as keys. Example: from collections import defaultdict words = ["eat", "tea", "tan", "ate", "nat", "bat"] anagrams = defaultdict(list) for word in words: key = ''.join(sorted(word)) anagrams[key].append(word) print(list(anagrams.values())) # [['eat', 'tea', 'ate'], ['tan', 'nat'], ['bat']]
174
How Long Have You Spent Coding Primarily in Python?
Reference answer
An engineer may code for years but it is likely that they worked with different languages. Such advanced Python programming interview questions are essential to understand how much time they coded in Python specifically so you know that they are comfortable with the language.
175
What is lambda in Python?
Reference answer
A lambda in Python is a small, anonymous function defined using the lambda keyword. It can take any number of arguments but returns a single expression. Lambdas are often used for short, inline operations, such as with map() or filter().
176
What is the __init__() function in Python?
Reference answer
All classes in Python have a function called __init__(), which is always executed when the class is being initiated. We can use the __init__() function to assign values to object properties, or other operations that are necessary to do when the object is being created.
177
What are Python metaclasses?
Reference answer
Metaclasses are "classes of a class" that define how a class behaves. They're a complex feature used to modify class creation.
178
In your experience, what Python coding standards and best practices do you follow to ensure code quality and maintainability?
Reference answer
I adhere to PEP 8 for code style, use docstrings for documentation, and follow the DRY (Don't Repeat Yourself) principle to ensure clean and maintainable code.
179
What is monkey patching?
Reference answer
In Python, the term monkey patch only refers to dynamic modifications of a class or module at run-time.
180
How do you convert a string to a floating-point number in python?
Reference answer
The Python float function will convert a string to a floating-point number. x = '100.12345' float(x)
181
Can Python Be Used for Web Client and Web Server Programming? What Is Best for Python?
Reference answer
Python can not be used for web client programming. It is only used for back-end development.
182
How can Python code style and quality be guaranteed?
Reference answer
Use linters like pylint and formatters like black to enforce code quality and style. Example: # Format Python code with Black black your_script.py # Check Python code for errors and style issues with Pylint pylint your_script.py
183
How do you floor a number in Python?
Reference answer
To floor a number in Python, you can use the math.floor() function, which returns the largest integer less than or equal to the given number. - floor() method in Python returns the floor of x i.e., the largest integer not greater than x. - Also, The method ceil(x) inPython returns a ceiling value of x i.e., the smallest integer greater than or equal to x. import math n = 3.7 F_num = math.floor(n) print(F_num) Output 3
184
How do you add an element to a list in Python?
Reference answer
You can use the append() method to add an element to the end of a list.
185
What is PEP 8 and its importance?
Reference answer
PEP means Python Enhancement Proposal, is an official design document that provides information for the Python community. It typically documents the style guidelines for Python code.
186
Write a Python function to check if a number is prime.
Reference answer
Sample Answer: A prime number is defined as a number greater than 1 that has no divisors other than 1 and itself. To check if a number is prime, you can iterate from 2 up to the square root of the number, testing for any divisors. This method is efficient because if a number has a divisor larger than its square root, the corresponding quotient must be smaller than the square root. Here is how you can implement the code: def is_prime(n): if n <= 1: return False for i in range(2, int(n**0.5) + 1): if n % i == 0: return False return True
187
How do you define a function in Python?
Reference answer
A function is a block of code which is executed only when it is called. To define a Python function, the def keyword is used. Example: def Newfunc(): print("Hi, Welcome to Edureka") Newfunc(); #calling the function Output: Hi, Welcome to Edureka
188
Is Indentation Required in Python?
Reference answer
Yes, indentation is required in Python. A Python interpreter can be informed that a group of statements belongs to a specific block of code by using Python indentation. Indentations make the code easy to read for developers in all programming languages but in Python, it is very important to indent the code in a specific order.
189
What are Python documentation strings?
Reference answer
By function, documentation strings are similar to comments. The only difference is that you use triple quotes """, not a hash-tag, to create a documentation string. A candidate should also specify that documentation strings are not executed because they are not assigned to a variable.
190
Could you provide specific examples of profiling tools or techniques you used to identify performance bottlenecks in the project?
Reference answer
In that project, we used Python's built-in cProfile and timeit modules extensively. cProfile helped us pinpoint slow functions, while timeit allowed us to measure the execution time of specific code snippets.
191
What is a for loop? How does it work in Python?
Reference answer
A for loop is used to iterate over a sequence (e.g., list, tuple, string) and perform an action for each element.
192
What is slicing in Python?
Reference answer
Python Slicing is a technique used to extract a portion of a sequence such as a string, list, tuple or range. It allows you to specify a starting index, an ending index and an optional step value. Syntax: substring = s[start : end : step]
193
Reverse first 'k' elements of a queue
Reference answer
To see the code solution in action, go to the original post Explanation Check for invalid input, i.e., if the queue is empty, if k is greater than the queue, and if k is negative on line 2. If the input is valid, start by creating a Stack. The available stack functions are: - Constructor: myStack() - Push Elements: push(int) to add elements to the stack. - Pop elements: pop() to remove or pop the top element from the stack. - Check if empty: isEmpty() returns true if the stack is empty and false otherwise. - Return back: back() returns the element that has been added at the end without removing it from the stack. - Return front: front() returns the top element (that has been added at the beginning) without removing it from the stack. Our function reverseK(queue, k) takes queue as an input parameter. k represents the number of elements we want to reverse. The available queue functions are: Constructor: myQueue(size) size should be an integer specifying the size of the queue.Enqueue: enqueue(int) Dequeue: dequeue() Check if empty: isEmpty() Check size: size() Now, moving on to the actual logic, dequeue the first k elements from the front of the queue and push them in the stack we created earlier using stack.push(queue.dequeue()) in line 8. Once all the k values have been pushed to the stack, start popping them and enqueueing them to the back of the queue sequentially. We will do this using queue.enqueue(stack.pop()) in line 12. At the end of this step, we will be left with an empty stack and the k reversed elements will be appended to the back of the queue. Now we need to move these reversed elements to the front of the queue. To do this, we used queue.enqueue(queue.dequeue()) in line 16. Each element is first dequeued from the back
194
Can you explain common searching and graph traversal algorithms in Python?
Reference answer
Python has a number of different powerful algorithms for searching and graph traversal, and each one deals with different data structures and solves different problems. I'll explain them here: - Binary Search: If you need to quickly find an item in a sorted list, binary search is your go-to. It works by repeatedly dividing the search range in half until the target is found. - AVL Tree: An AVL tree keeps things balanced, which is a big advantage if you're frequently inserting or deleting items in a tree. This self-balancing binary search tree structure keeps searches fast by making sure the tree never gets too skewed. - Breadth-First Search (BFS): BFS is all about exploring a graph level by level. It's especially useful if you're trying to find the shortest path in an unweighted graph since it checks all possible moves from each node before going deeper. - Depth-First Search (DFS): DFS takes a different approach by exploring as far as it can down each branch before backtracking. It's great for tasks like maze-solving or tree traversal. - A* Algorithm: The A* algorithm is a bit more advanced and combines the best of both BFS and DFS by using heuristics to find the shortest path efficiently. It's commonly used in pathfinding for maps and games.
195
Explain the difference between @staticmethod and @classmethod decorators. Give code examples.
Reference answer
- @staticmethod defines a method that does not access the instance or class. - @classmethod receives the class as the first argument (cls) and can modify class state. Example: class Example: @staticmethod def static_method(): return "static method called" @classmethod def class_method(cls): return f"class method called from {cls.__name__}" print(Example.static_method()) # static method called print(Example.class_method()) # class method called from Example
196
WAP (Write a program) which takes a sequence of numbers and check if all numbers are unique.
Reference answer
You can do this by converting the list to set by using set() method and comparing the length of this set with the length of the original list. If found equal, return True. def check_distinct(data_list): if len(data_list) == len(set(data_list)): return True else: return False; print(check_distinct([1,6,5,8])) #Prints True print(check_distinct([2,2,5,5,7,8])) #Prints False
197
Write a Python code to implement a binary search algorithm
Reference answer
def binary_search(arr, target): low, high = 0, len(arr) - 1 while low <= high: mid = (low + high) // 2 if arr[mid] < target: low = mid + 1 elif arr[mid] > target: high = mid - 1 else: return mid return -1 print(binary_search([1, 2, 3, 4, 5], 3)) # 2
198
7. How is memory managed in Python?
Reference answer
Memory is managed in Python through a combination of private heap space, reference counting, and a cyclic garbage collector. Python has a private heap space where all its objects and data structures are stored. Ensuring a safe and efficient memory management process, this area is only accessible by the Python interpreter. Reference counting is one of the techniques Python uses to manage memory. Every object has a count of the number of references pointing to it. Memory is freed up, when this count drops to zero. This technique alone can't handle reference cycles, where two objects refer to each other. Python incorporates a cyclic garbage collector, to address the limitations of reference counting. This garbage collector identifies and cleans up reference cycles, ensuring that memory is not leaked. The garbage collector runs periodically and checks for objects that are no longer in use. Memory pools are used for fixed-size blocks, optimizing memory allocation. This reduces fragmentation and speeds up memory allocation. Memory management in Python is automatic. Developers do not need to allocate or deallocate memory explicitly. Understanding how it works helps in writing more efficient code.
199
58. Can you explain how Web Scraping is done using Python?
Reference answer
Web scraping using Python is achieved through libraries like BeautifulSoup and requests. First send a request to the target website using the `requests` library to obtain its HTML content. Once the content is fetched, parse and navigate it using Beautiful Soup. This library provides tools to search for specific tags, classes, and IDs, allowing you to extract the data you need. Ensure you follow the website's `robots.txt` guidelines and avoid overwhelming the server with rapid, successive requests. Check the website's terms of service, as scraping is not always permitted. Use headers and time delays in your requests, if required, to mimic human browsing behavior and reduce the chances of getting banned.
200
How do you install Python packages?
Reference answer
Python packages can be installed using pip, Python's package installer, with commands like pip install .