* View counts were reset on 18 October 2026, when Interviewplus moved to interviewplus.app. Votes were not affected.
Answer
In Python, a list and a tuple are both used to store a collection of items/values. The main difference is that a list is mutable, meaning you can add, remove, or modify items in the list, while a tuple is immutable, meaning you cannot modify its contents once it is created. Lists are created using square brackets [], and tuples are created using parentheses (). Another difference is that tuples are generally faster and use less memory than lists, but they are not as versatile as lists because of their immutability.
Answer
In Python, exceptions can be handled using try-except blocks. Here's an example of how to catch a specific exception:
try:
x = int("a")
except ValueError:
print("Oops! Invalid input. Please enter a number.")In this example, the try block attempts to convert the string "a" to an integer using the int() function, which will raise a ValueError since "a" cannot be converted to an integer. The except block catches the ValueError exception and prints an error message.
Answer
To iterate over a dictionary in Python, you can use a for loop with the items() method. The items() method returns a list of key-value pairs in the dictionary, which can be iterated over. Here's an example:
my_dict = {"apple": 3, "banana": 2, "orange": 5}
for key, value in my_dict.items():
print(key, value)In this example, we use the items() method to get a list of key-value pairs in the my_dict dictionary. The for loop then iterates over this list, assigning the key to the variable key and the value to the variable value. The loop body simply prints out the key and value for each item.
Answer
To implement a web scraper using Python, you can use the popular web scraping framework, Beautiful Soup. Here's an example of how to use Beautiful Soup to extract data from a website and store it in a CSV file:
import requests
from bs4 import BeautifulSoup
import csv
# URL of the website to scrape
url = "https://www.example.com"
# Send a request to the website and get the HTML response
response = requests.get(url)
# Parse the HTML response using Beautiful Soup
soup = BeautifulSoup(response.content, 'html.parser')
# Find all the data elements you want to scrape using Beautiful Soup selectors
data = soup.select("div.my-data")
# Open a CSV file and write the data to it
with open("data.csv", "w") as csv_file:
writer = csv.writer(csv_file)
writer.writerow(["Data"])
for item in data:
# Extract the text content of the data element
data_text = item.get_text()
# Write the data to the CSV file
writer.writerow([data_text])In this example, we first import the required libraries, including requests for sending HTTP requests, Beautiful Soup for parsing the HTML response, and csv for writing the data to a CSV file. We then specify the URL of the website we want to scrape and send a request to get the HTML response.
Next, we use Beautiful Soup selectors to find the data elements we want to scrape from the HTML response. In this example, we're selecting all the div elements with a class of my-data.
Finally, we open a CSV file and use the csv module to write the data to it. In this example, we're writing each data element to a new row in the CSV file.
Note that web scraping may be illegal or against the terms of service of some websites, so it's important to check the legality and ethical implications of web scraping before doing so.
Answer
In Python, memory is managed using an automatic memory management system called reference counting. The Python interpreter keeps track of all objects created in the program and deletes them automatically when they are no longer needed or when their reference count becomes zero. When an object is assigned to a variable or passed as an argument to a function, its reference count is incremented, and when the variable goes out of scope or the function call returns, the reference count is decremented. When the reference count reaches zero, the memory occupied by the object is freed and returned to the system. In addition to reference counting, Python also uses a garbage collector to reclaim memory that is no longer reachable by the program.
Answer
The "append" method adds an element to the end of the list, while the "extend" method appends each element from an iterable (e.g. another list) to the end of the list.
Here's an example:
# Using the append method my_list = [1, 2, 3] my_list.append(4) print(my_list) # Output: [1, 2, 3, 4] # Using the extend method my_list = [1, 2, 3] other_list = [4, 5, 6] my_list.extend(other_list) print(my_list) # Output: [1, 2, 3, 4, 5, 6]
In the first example, the "append" method is used to add the integer 4 to the end of the "my_list" list. In the second example, the "extend" method is used to append each element from the "other_list" iterable to the end of the "my_list" list.
Answer
with open('filename.txt', 'r') as file:
for line in file:
print(line)In this example, we use the open() function to open the file in read mode ('r'). We then use a with statement to ensure that the file is properly closed after we are finished with it.
We then use a for loop to iterate over each line in the file, using the print() function to display the contents of each line. This method of reading a file is memory-efficient because it reads and processes one line at a time, rather than loading the entire file into memory at once.
Answer
Inheritance is a fundamental feature of object-oriented programming that allows creating a new class by inheriting properties and methods from an existing class. The new class is called the child or subclass, and the existing class is called the parent or superclass.
In Python, inheritance is implemented by creating a new class that inherits properties and methods from the parent class. The child class can then add new properties and methods or modify the existing ones.
Here's an example of inheritance in Python:
class Animal:
def __init__(self, name, age):
self.name = name
self.age = age
def speak(self):
print("")
class Dog(Animal):
def __init__(self, name, age, breed):
super().__init__(name, age)
self.breed = breed
def speak(self):
print("Woof!")
class Cat(Animal):
def __init__(self, name, age, color):
super().__init__(name, age)
self.color = color
def speak(self):
print("Meow!")
dog = Dog("Buddy", 3, "Labrador")
print(dog.name) # Output: Buddy
print(dog.age) # Output: 3
print(dog.breed) # Output: Labrador
dog.speak() # Output: Woof!
cat = Cat("Luna", 2, "Black")
print(cat.name) # Output: Luna
print(cat.age) # Output: 2
print(cat.color) # Output: Black
cat.speak() # Output: Meow!In this example, we have a parent class Animal that has an __init__ method to initialize the name and age of an animal and a speak method that is empty. The child classes Dog and Cat inherit from the Animal class and add new properties and methods to it. The Dog class adds a breed property and overrides the speak method to print "Woof!" while the Cat class adds a color property and overrides the speak method to print "Meow!". We create instances of the Dog and Cat classes and call their respective methods to see the output.
Answer
To develop a machine learning model in Python that can predict the price of a stock or cryptocurrency, we need to follow the following steps:
1. Collect the data: We need to collect historical data and market trends for the stock or cryptocurrency that we want to predict the price for. We can use APIs like Alpha Vantage or Yahoo Finance to collect the data.
2. Data preprocessing: Once we have the data, we need to preprocess it. This involves cleaning the data, removing any missing values, and converting the data into a format that can be used by our machine learning algorithm.
3. Feature engineering: In this step, we extract features from the data that can be used by our machine learning algorithm to make predictions. This could include technical indicators like moving averages, relative strength index (RSI), and Bollinger Bands.
4. Split the data: Next, we split the data into training and testing sets. The training set is used to train our machine learning algorithm, while the testing set is used to evaluate the performance of the model.
5. Train the model: We can use various machine learning algorithms like linear regression, decision trees, or neural networks to train our model on the training data.
6. Evaluate the model: Once the model is trained, we need to evaluate its performance on the testing data. We can use metrics like mean squared error (MSE), root mean squared error (RMSE), and mean absolute error (MAE) to evaluate the performance of the model.
7. Make predictions: Finally, we can use the trained model to make predictions on new data.
Here's an example code snippet that demonstrates how to use linear regression to predict the price of a stock using historical data:
import pandas as pd
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error
# Collect data from Alpha Vantage API
# Preprocess the data
# Feature engineering
# Split the data into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# Train the model
model = LinearRegression()
model.fit(X_train, y_train)
# Evaluate the model
y_pred = model.predict(X_test)
mse = mean_squared_error(y_test, y_pred)
rmse = np.sqrt(mse)
print('Root Mean Squared Error:', rmse)
# Make predictions
new_data = pd.read_csv('new_data.csv')
new_data = feature_engineering(new_data)
y_pred = model.predict(new_data)
print('Predicted price:', y_pred)Note that this is just a simple example, and there are many ways to improve the accuracy of the model, such as using more complex algorithms, adding more features, and tuning hyperparameters.
Answer
In Python, a namespace is a container that holds a set of names, such as variables, functions, and classes, and provides a way to avoid naming collisions. Namespaces can be thought of as dictionaries that map names to objects. Every module, function, and class in Python has its own namespace. When a name is referenced, Python searches the namespaces in a particular order known as the "LEGB rule" (local, enclosing, global, built-in) to resolve the reference. This helps to avoid conflicts between variables and functions that have the same name but are used for different purposes.
For example, in a Python program, you could have a function called "sum" and a variable called "sum". The function "sum" could be defined in the global namespace, and the variable "sum" could be defined in a local namespace. When you call "sum" in your program, Python will first look in the local namespace, then in the global namespace, and finally in the built-in namespace to resolve the reference.
Answer preview
In Python, variables can have local or global scope, depending on where they are defined and used. A local variable is a variable that is defined inside a function and can only be accessed from within that function. It is created when the function is called and is destroyed when the function returns. A local variable…
Sign in to view this answer
Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.
Answer preview
In this example, the fibonacci() function takes an integer n as input and returns the n-th number in the Fibonacci sequence. If n is less than or equal to 1, the function simply returns n. Otherwise, it recursively calls itself with n-1 and n-2 as input and returns the sum of the results.
Sign in to view this answer
Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.
Answer preview
To create a chatbot using Python, you can use the Natural Language Toolkit (NLTK) library, which provides a wide range of tools for natural language processing. Here's an example of how you can create a simple chatbot using NLTK: In this example, we define a list of patterns and responses for the chatbot to use in its…
Sign in to view this answer
Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.
Answer preview
In the output, 0o represents the prefix for octal numbers. The output 0o173 is the octal representation of the decimal number 123.
Sign in to view this answer
Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.
Answer preview
Here, we initialize two variables: max_num to the first element of the array and second_max to negative infinity. We then iterate through the array and compare each element with the current max_num. If an element is greater than max_num, we update second_max to the current max_num and update max_num to the current…
Sign in to view this answer
Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.
Answer preview
Here is an example of implementing a simple RESTful API using Python and Flask, with CRUD (Create, Read, Update, Delete) operations and token-based authentication. First, we need to install the Flask and its extension Flask-RESTful by running the following commands in the terminal: Then, let's create a file called…
Sign in to view this answer
Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.
Answer preview
In Python, a decorator is a function that takes another function and extends the behavior of the latter function without explicitly modifying it. Decorators allow for the dynamic modification of a function or a class at runtime. Here's an example of a decorator function that adds timing functionality to another…
Sign in to view this answer
Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.
Answer preview
In Python, "range" and "xrange" are both used to generate a sequence of numbers. The main difference between the two is that "range" returns a list, while "xrange" returns a generator object. The "range" function creates a list of numbers between the specified start and end values (exclusive) with a given step size…
Sign in to view this answer
Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.
Answer preview
In Python, multithreading can be handled using the threading module. This module provides a way to create new threads and manage them. Here's an example of how to use the threading module to create a simple program that runs two threads: In this example, the print_numbers function prints the numbers from 1 to 10, and…
Sign in to view this answer
Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.
Answer preview
In Python, a lambda function is a small anonymous function that can have any number of arguments, but can only have one expression. It is also known as an inline function or a lambda abstraction. Here is an example of a lambda function that takes two arguments and returns their sum: In the above example, add is a…
Sign in to view this answer
Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.
Answer preview
In Python, a generator function is a special type of function that can be used to generate a sequence of values on-the-fly, rather than computing them all at once and storing them in memory. This is useful for generating large sequences of values that would be impractical to store in memory all at once. A generator…
Sign in to view this answer
Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.
Answer preview
This code defines a Node class to represent each node of the binary tree, with a val attribute for the node's value, a left attribute for the left child node, and a right attribute for the right child node. The right_view function takes the root node of the binary tree as an argument and returns a list of values…
Sign in to view this answer
Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.
Answer preview
This code takes the number of mobile numbers n as input and then loops over each number to extract the last 10 digits, add the country code and format it. The standardized numbers are then added to a list, which is sorted in ascending order. Finally, the sorted numbers are printed in the standard format.
Sign in to view this answer
Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.
Answer preview
Here's an example of a data analysis tool using Python that can process large amounts of data, visualize it using charts and graphs, and provide insights and recommendations. First, we'll need to install some packages using pip: Next, let's assume we have a CSV file with data about customer purchases from an…
Sign in to view this answer
Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.
Answer preview
In Python, you can work with JSON data using the built-in json module. This module provides methods for encoding and decoding JSON data. Here is an example of loading and parsing JSON data: In the above example, we first import the json module. We then define some sample JSON data as a string. We use the json.loads()…
Sign in to view this answer
Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.
Answer preview
The function first converts the input num to a string using the str() function. It then determines the length of the string and initializes an empty string to hold the formatted number. The function then iterates over each character in the string, adding the character to the formatted number string. When the function…
Sign in to view this answer
Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.
Answer preview
Here is the Python code for the param_count function that takes a variable number of parameters and returns the number of arguments it was called with: In this function, the *args parameter allows the function to accept any number of arguments. The len function is used to return the number of arguments that were…
Sign in to view this answer
Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.
Answer preview
To build a web application using Python that allows users to search for and book flights, we can follow these steps: 1. Choose a web framework for building the application. In this example, we will use the Flask framework. 2. Design the database schema for storing flight information, such as flight number, departure…
Sign in to view this answer
Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.
Answer preview
In Python, an iterable is an object that can be iterated over using a loop, while an iterator is an object that defines how the iteration is done. The most common built-in iterables in Python include lists, tuples, sets, and dictionaries. To create a custom iterator, we need to define a class that implements the…
Sign in to view this answer
Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.
Answer preview
Descriptors are a powerful feature of Python that allow us to customize the behavior of attributes in a class. In Python, attributes are simply names that reference objects, and descriptors allow us to intercept and customize the access and modification of those objects. Here's an example of a descriptor class: This…
Sign in to view this answer
Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.
Answer preview
Asynchronous programming is a style of concurrent programming that allows the code to run without waiting for a task to complete. Python provides the asyncio module for asynchronous programming. Here is an example of using asyncio to create a coroutine and run it asynchronously: In this example, we define a coroutine…
Sign in to view this answer
Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.
Answer preview
A recommendation engine is a system that analyzes a user's preferences and behavior to suggest items that they may be interested in. Here's an example of how to build a simple recommendation engine using Python: 1. Collect Data: Collect user data such as purchase history, ratings, and search queries. Collect item data…
Sign in to view this answer
Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.
Answer preview
This code defines a function is_friday_13th that takes a datetime.date object and returns True if it is a Friday the 13th, and False otherwise. The function checks if the given date is the 13th of the month and a Friday by using the day and weekday methods of the date object. The code then tests the function for a…
Sign in to view this answer
Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.
Answer preview
Sure, here is an example of creating a simple game using Pygame in Python: This game creates a player and an enemy, and the player can move left and right using the arrow keys to avoid colliding with the enemy. The game keeps score and displays it on the screen. When the player collides with the enemy, the game is…
Sign in to view this answer
Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.
Answer preview
The Global Interpreter Lock (GIL) in Python is a mechanism used by the Python interpreter to ensure that only one thread executes Python bytecode at a time. The GIL is a lock that is acquired by the Python interpreter before executing any Python code, and it is released when the code execution is complete. The purpose…
Sign in to view this answer
Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.
Answer preview
Here's a Python function that accepts a string as input and checks if any word in the sentence contains duplicate letters. The function splits the input sentence into words and then checks each word for duplicates using a set: We first split the sentence into words using the split() method. Then, for each word, we…
Sign in to view this answer
Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.
Answer preview
Working with databases in Python involves using libraries like SQLite, MySQL, PostgreSQL, or Oracle, among others. One common way of working with databases in Python is using Object-Relational Mapping (ORM) libraries like SQLAlchemy, which provide a high-level interface to work with databases in Python. Here is an…
Sign in to view this answer
Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.
Answer preview
Sure, here's an example Python code to calculate the area of a triangle based on its base and height: This code defines a function called calculate_triangle_area that takes two parameters: the base and height of the triangle. It then calculates the area of the triangle using the formula 0.5 * base * height and returns…
Sign in to view this answer
Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.
Answer preview
Sure! Here's an example of how to build a sentiment analysis tool using Python. First, we need to install the necessary libraries. We will use the Natural Language Toolkit (NLTK) for text processing and the Scikit-Learn library for machine learning: Next, we need to download the necessary NLTK data: Now, let's write…
Sign in to view this answer
Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.
Answer preview
The find_largest function takes three numbers as input parameters and returns the largest of the three using if conditions to check which is greater.
Sign in to view this answer
Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.
Answer preview
Here's an example Python program to find the factorial of a number using a recursive function: Output: In this program, we define a function called factorial that takes an integer parameter n. The function uses recursion to calculate the factorial of n, which is defined as the product of all positive integers less…
Sign in to view this answer
Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.
Answer preview
In this program, the user is prompted to enter the lower and upper range of the interval. Then, a for loop is used to iterate over all the numbers in the interval. For each number, the program calculates the sum of the cubes of its digits, and checks whether this sum is equal to the number itself. If it is, the number…
Sign in to view this answer
Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.
Answer preview
You can use the built-in ord() function to find the ASCII value of a character in Python. Here's an example code: In this code, the input() function is used to take a single character as input from the user. Then, the ord() function is used to find the ASCII value of the character, and the result is stored in the…
Sign in to view this answer
Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.
Answer preview
To find all files with .txt extension present inside a directory in Python, you can use the os module. Here's an example code: In this code, we first specify the directory path using the directory variable. We then loop through all the files in the directory using the os.listdir() method. For each file, we check if it…
Sign in to view this answer
Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.
Answer preview
To develop a web-based project management system using Python and a project management framework, we can use the Django web framework. Here are the general steps for creating such a system: 1. Set up a new Django project and create a new Django app within the project for the project management system. 2. Define the…
Sign in to view this answer
Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.
Go further with Python
Python code challenges
10 challenges with answers
Behavioral Questions
10 questions with answers
Cultural Fit Questions
10 questions with answers
Competency-Based Questions
10 questions with answers
Motivational Questions
10 questions with answers
Communication Skills Questions
10 questions with answers
Scenario-Based Questions
10 questions with answers
Problem-Solving and Analytical Questions
10 questions with answers
Ethical and Integrity Questions
10 questions with answers
Industry-Specific Questions
10 questions with answers
Leadership and Management Questions
10 questions with answers
Personal Questions
10 questions with answers
Python interview questions and answers
This page lists 45 Python interview questions with answers, ordered from junior to senior level. Commonly asked questions include "What is the difference between a list and a tuple in Python?", "How do you handle exceptions in Python? Can you provide an example of how to catch a specific exception?" and "How do you iterate over a dictionary in Python? Can you provide an example?".
Other frequently asked questions include "How is Memory managed in Python?", "Can you explain the difference between "append" and "extend" methods in a list in Python? Can you provide an example?" and "Can you explain the difference between local and global variables in Python? Can you provide an example?". Review each answer and consider how you would adapt it to your own experience.
Practise Python in a mock interview
Answer questions one at a time and receive a score with written feedback on each answer.