In this tutorial, we have laid down the top Python programming interview questions usually asked by the top five IT companies. You’ll find 10 questions with their answers for each of Google, Microsoft, Amazon, Facebook, and Apple. Let’s start the Google interview questions and answers first.
50 Interview Questions With Answers
Python is the number one programming language in the world. It is one of the most sought-after IT skills by employers. Apart from learning it, it is essential to practice with the latest questions and answers. And what can be better than taking on questions asked by the top companies? Let’s start.
10 Google Python Programming Interview Questions
Here, we bring you a small subset of questions. However, this should give you a fair idea of what companies ask and what you should be preparing.
1. What is the difference between lists and sets in Python?
Answer:
Lists maintain order and permit duplicates, whereas sets lack order and prohibit duplicates.
my_list = [1, 2, 2, 3, 4]
my_set = {1, 2, 3, 4}
2. Explain the purpose of the collections
module in Python.
Answer:
The collections module provides specialized container datatypes.
# Example: Counter for counting occurrences.
from collections import Counter
result = Counter("abracadabra")
3. How can you handle exceptions in Python? Provide an example.
Answer:
Use the Python try-except block.
try:
result = 10 / 0
except ZeroDivisionError as e:
print(f"Error: {e}")
4. What is the Global Interpreter Lock (GIL) in Python, and how does it impact multithreading?
Answer:
The Global Interpreter Lock (GIL) serves as a mutual exclusion mechanism, safeguarding access to Python objects and restricting the execution of Python bytecode by multiple native threads simultaneously. This means that even in a multithreaded environment, only one thread can run Python bytecode, impacting the performance of tasks that require a lot of processing power. It’s like having a single lane for traffic, which can slow things down, especially for tasks that need a lot of computing.
5. How does memory management work in Python?
Answer:
Python uses a private heap space for memory management. The memory manager handles allocation and deallocation, and a garbage collector automatically reclaims unused memory.
# Example: Automatic memory management
my_list = [1, 2, 3]
6. What is the purpose of the __init__
method in Python?
Answer:
The __init__
method is a special method in Python classes that is called when an object is created. It initializes the attributes of the object.
# Example: Using __init__ method
class MyClass:
def __init__(self, value):
self.value = value
obj = MyClass(42)
7. Explain the difference between shallow copy and deep copy.
Answer:
Shallow copy creates a new object but does not copy nested objects. Deep copy recursively copies all objects referenced by the original.
# Example: Shallow copy vs Deep copy
import copy
original_list = [[1, 2, 3], [4, 5, 6]]
shallow_copy = copy.copy(original_list)
deep_copy = copy.deepcopy(original_list)
8. How does exception handling work in Python?
Answer:
Python uses try, except, and finally blocks for exception handling. The try block executes the code, and in the event of an exception, the exception block handles the execution.
# Example: Exception handling
try:
result = int("abc")
except ValueError as e:
print(f"Error: {e}")
9. What is the purpose of the map
and filter
functions in Python?
Answer:
The map function applies a given function to all items in an input list, while the filter function filters elements based on a specified function.
# Example: Using map and filter
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, numbers))
even = list(filter(lambda x: x % 2 == 0, numbers))
10. Explain the concept of list comprehensions in Python.
Answer:
List comprehensions provide a concise way to create lists, using an expression followed by at least one for
clause and zero or more if
clauses.
# Example: List comprehension
squared = [x**2 for x in range(5) if x % 2 == 0]
Absolutely! Let’s continue with questions and answers for Amazon.
10 Amazon Python Programming Interview Questions
In this section for Amazon interview questions, you will find questions on various topics. These include multiple inheritances, the purpose of the ‘with’ statement for resource management, and understanding decorators for modifying function behavior in Python interviews at Amazon.
Also Read – Top Amazon QAE Interview Questions and Answers
1. How does Python support multiple inheritances?
Answer:
Python supports multiple inheritances by allowing a class to inherit from more than one base class, enabling the derived class to inherit attributes and methods from all its base classes.
# Example: Multiple inheritance
class A:
pass
class B:
pass
class C(A, B):
pass
2. What is the purpose of the with
statement in Python?
Answer:
The with
statement is used for resource management. It guarantees the execution of a designated code block within a specific context, handling resource cleanup automatically.
# Example: Using with statement for file handling
with open('example.txt', 'r') as file:
content = file.read()
3. Explain the use of decorators in Python.
Answer:
Decorators are a way to modify or extend the behavior of functions or methods. They are applied using the @decorator
syntax and are commonly used for code reuse and to modify function behavior.
# Example: Simple decorator
def my_decorator(func):
def wrapper():
print("Something is happening before the function is called.")
func()
print("Something is happening after the function is called.")
return wrapper
@my_decorator
def say_hello():
print("Hello!")
say_hello()
4. How does Python’s garbage collection work?
Answer:
Python uses automatic memory management, and the garbage collector is responsible for reclaiming memory occupied by objects that are no longer in use.
# Example: Garbage collection
import gc
gc.collect()
5. How do append() and extend() differ when adding items to lists in Python?
Answer:
While both methods add elements to a list, they approach it in distinct ways:
- append() treats its argument as a single entity, placing it at the end of the list as a whole unit.
- extend() unfurls its argument, integrating each element within it into the list separately.
# Example: append() vs extend()
ids1 = [11, 21, 31]
ids2 = [14, 25, 36]
ids1.append(ids2) # [11, 21, 31, [14, 25, 36]]
ids1.extend(ids2) # [11, 21, 31, 14, 25, 36]
6. How do you handle missing values in a Pandas data frame?
Answer:
We can use the dropna()
or fillna()
methods in Pandas. Let’s take an example to understand:
# Drop rows with missing values
df_cleaned = df.dropna()
# Fill missing values with a specific value (e.g., mean)
df_filled = df.fillna(df.mean())
7. What is the purpose of the lambda function in Python?
Answer:
The lambda
function is an anonymous function created using the lambda
keyword. It is often used for short-term operations and is commonly employed in functions like map
, filter
, and sort
.
# Example: Using lambda function
square = lambda x: x**2
result = square(5)
8. How can you handle file I/O in Python?
Answer:
File I/O in Python is performed using the open()
function to open a file, and methods like read()
, write()
, and close()
to read from or write to the file.
# Example: Reading from a file
with open('example.txt', 'r') as file:
content = file.read()
9. Write a Python script to fetch product info (title, price, rating) from the HTML product pages on Amazon with proper error handling.
Answer:
To get the product info (title, price, rating) from the HTML product pages, we can use the BeautifulSoup library for parsing. Additionally, the requests library can also fetch the HTML content from the web. Here’s a script with error handling:
import requests
from bs4 import BeautifulSoup
def get_product(url):
try:
# Fetch HTML content
resp = requests.get(url)
resp.raise_for_status() # Raise an exception for HTTP errors
# Parse HTML content
soup = BeautifulSoup(response.content, 'html.parser')
# Extract product information
title = soup.find('span', {'id': 'productTitle'}).get_text(strip=True)
price = soup.find('span', {'id': 'priceblock_ourprice'}).get_text(strip=True)
rating = soup.find('span', {'data-asin': 'B07V4GKFDH'}).get_text(strip=True) # Adjust as per the actual HTML
return {'title': title, 'price': price, 'rating': rating}
except requests.RequestException as req_err:
print(f"Request Error: {req_err}")
except Exception as err:
print(f"Error: {err}")
return None
# Let's call the get_product
if __name__ == "__main__":
prod_url = "Put some line to an example product"
prod_info = get_product(prod_url)
if product_info:
print("Product Info:")
print(f"Title: {prod_info['title']}")
print(f"Price: {prod_info['price']}")
print(f"Rating: {prod_info['rating']}")
10. What is the purpose of the __str__
& __repr__
methods in Python?
Answer:
The __str__
method is used to return a human-readable string representation of an object, while the __repr__
method returns an unambiguous string representation that should be used for debugging.
# Example: Using __str__ and __repr__
class MyClass:
def __str__(self):
return "This is a MyClass object"
def __repr__(self):
return "MyClass()"
Next, let’s move on to Microsoft.
10 Microsoft Python Programming Interview Questions
Discover questions on Python’s list comprehension for streamlined list creation, efficient handling of large log files using generators, and the use of the @property decorator for creating read-only properties in Microsoft Python interviews.
1. How does Python’s list comprehension feature make list creation smoother for programmers?
Answer:
It’s like a shortcut for building lists directly within a single line of code, combining a loop and filtering conditions seamlessly. Here’s a breakdown:
Imagine you’re coding a game and need a list of active player scores:
– Traditional approach:
high_scores = [] # Create an empty list
for player in players: # Loop through each player
if player.status == "active": # Check if they're active
high_scores.append(player.score) # Add their score to the list
– List comprehension approach:
high_scores = [player.score for player in players if player.status == "active"]
Both create the same list, but list comprehension does it in a single line, making code more concise and readable for programmers.
2. How can you use generators in Python to analyze a large Azure log file line by line without filling up all the memory at once?
Answer:
In Python, we can use generators to analyze a large Azure log file line by line without loading the entire file into memory simultaneously. Generators allow you to iterate over the file one line at a time, enabling efficient memory usage.
Here’s an example of how to implement this:
def read_log(file_path):
with open(file_path, 'r') as log_file:
for line in log_file:
yield line.strip()
# Reading the azure log file in a memory efficient way
if __name__ == "__main__":
log_file = "path/azure.log"
# Use the generator to process each line in the log file
log_gen = read_log(log_file)
for line in log_gen:
# Do log analysis for each line
print(line)
In this example:
- The
read_log
function is a generator function that opens the log file and yields each line one by one using theyield
statement. - The
with open(file_path, 'r') as log_file:
ensures that the file is properly closed after iteration is complete or an exception is raised. - The
yield line.strip()
yields each line stripped of leading and trailing whitespaces.
Using this generator function, we can process the log file line by line without loading the entire file into memory. This is quite beneficial when dealing with large log files. Loading everything at once would be memory-intensive.
3. How can you handle multiple exceptions in Python?
Answer:
Multiple exceptions can be handled by specifying them as a tuple in the except
clause or by using a more general except
clause to catch any exception.
# Example: Handling multiple exceptions
try:
result = 10 / 0
except (ZeroDivisionError, ValueError) as e:
print(f"Error: {e}")
4. What is the purpose of the super()
function in Python?
Answer:
The super()
function is used to call a method from a parent class. It is often used in the __init__
method of a subclass to ensure that the initialization of the parent class is also executed.
# Example: Using super() in a subclass
class Parent:
def __init__(self):
print("Parent class initialization")
class Child(Parent):
def __init__(self):
super().__init__()
print("Child class initialization")
obj = Child()
5. Explain the use of the enumerate
function in Python.
Answer:
The enumerate
function is used to iterate over a sequence while keeping track of the index and the corresponding element. It returns tuples containing the index and element at that index.
# Example: Using enumerate
fruits = ['apple', 'banana', 'orange']
for index, fruit in enumerate(fruits):
print(f"Index: {index}, Fruit: {fruit}")
Must Read: Higher Order Functions in Python With Examples
6. What is a generator in Python, and how does it differ from a regular function?
Answer:
A generator is a special type of function that allows you to iterate over a potentially large set of data. It uses the yield keyword to return values one at a time, unlike regular functions that return all values at once.
# Example: Simple generator
def my_generator():
yield 1
yield 2
yield 3
gen = my_generator()
7. How does Python support multi-threading?
Answer:
Python supports multi-threading through the threading
module. However, due to the Global Interpreter Lock (GIL), multi-threading in Python is more suitable for I/O-bound tasks than CPU-bound tasks.
Check This: Python Multithreading Tutorial With Examples
# Example: Simple multithreading
import threading
def my_function():
print("Thread function")
thread = threading.Thread(target=my_function)
thread.start()
8. Explain the use of the @property
decorator in Python.
Answer:
The @property
decorator is used to turn a method into a read-only property. It allows you to access a method as if it were an attribute without calling it explicitly.
# Example: Using @property
class MyClass:
def __init__(self):
self._value = 42
@property
def value(self):
return self._value
obj = MyClass()
print(obj.value)
9. What is the purpose of NumPy in Python, and provide an example of creating a NumPy array?
Answer:
NumPy is a library for numerical operations in Python. It provides support for large, multi-dimensional arrays and matrices.
Let’s take the following example:
import numpy as npy
arr = npy.array([0.1, 0.2, 0.3])
10. Explain the use of the __name__
variable in Python.
Answer:
The __name__
variable is a special variable in Python that is automatically set by the interpreter. It helps us determine whether a Python file will run as the main program or as a module.
# Example: Using __name__
if __name__ == "__main__":
print("This script is being run as the main program.")
Next, let’s move on to Facebook.
10 Facebook Python Programming Interview Questions
In this section of Python programming interview questions, learn about the effective handling of emojis in iMessage, creating an algorithm for top influencers based on post engagement, and designing functions to categorize and process user posts, showcasing diverse skills in image classification and text analysis.
1. How do you read a CSV file into a Pandas DataFrame?
Answer:
We can use the pd.read_csv()
function to read a CSV file into a Pandas data frame. Here is the example code:
import pandas as pd
df = pd.read_csv('example.csv')
2. Given a DataFrame df
with columns ‘Name’, ‘Age’, and ‘Salary’, write a Python code snippet using Pandas to filter the rows where the ‘Salary’ is greater than 50000.
Answer:
This code uses boolean indexing to filter rows in the DataFrame where the ‘Salary’ column is greater than 50000.
import pandas as pd
# Assuming df is the DataFrame
df_filtered = df[df['Salary'] > 50000]
print(df_filtered)
3. How does Python’s zip function help programmers team up elements from different lists?
Answer:
It pairs up corresponding items from multiple iterables
, creating a new iterator of tuples where each tuple represents a matched couple. Here’s how it works in a gaming context:
Imagine you’re designing a simple customization feature:
– Lists of options:
hairstype = ["long", "short", "curly"]
eyecolor = ["blue", "green", "brown"]
– zip to create combinations:
combos = zip(hairtype, eyecolor)
– Accessing paired options:
# Create combos using the zip output
for i, (hair, eye) in enumerate(combos, start=1):
print(f"{i} {hair} hair and {eye} eyes")
Output:
1 long hair and blue eyes
2 short hair and green eyes
3 curly hair and brown eyes
4. Design a Python algorithm to efficiently identify frequently co-occurring words in a large dataset of user posts on Facebook.
Answer:
To identify frequently co-occurring words in a large dataset of user posts, we can use the following Python algorithm. This algo utilizes the concept of creating a co-occurrence matrix and then extracting the frequently co-occurring word pairs.
from collections import defaultdict as dd
from itertools import combinations as comb
def gen_word_mtx(posts):
mtx = dd(int)
for post in posts:
words = post.split()
for pair in comb(set(words), 2):
mtx[pair] += 1
return mtx
def word_pairs(mtx, threshold):
return [pair for pair, count in mtx.items() if count >= threshold]
# Example usage
if __name__ == "__main__":
posts = [
"I love coding and programming.",
"Coding is my passion.",
"Programming requires patience.",
"I enjoy programming challenges.",
# ... (more user posts)
]
mtx = gen_word_mtx(posts)
threshold = 2
word_pairs = word_pairs(mtx, threshold)
print("Frequent word pairs:")
for pair in pairs:
print(pair)
5. Explain the purpose of the __str__
and __repr__
methods in Python.
Answer:
The __str__
method is used to return a human-readable string representation of an object, while the __repr__
method returns an unambiguous string representation that should be used for debugging.
# Example: Using __str__ and __repr__
class MyClass:
def __str__(self):
return "This is a MyClass object"
def __repr__(self):
return "MyClass()"
6. Design a Python function to efficiently remove duplicate hashtags from a user’s Facebook post.
Answer:
To achieve this, we’ll define a function named remove_dup_hashtags
. This function takes a user’s post as input, divides it into words, and iterates through each word. The function keeps track of unique words, specifically focusing on hashtags. If a hashtag is encountered and it hasn’t been seen before, it’s added to the list of unique words. Words that don’t start with ‘#’ are also included in the list. Finally, the unique words are joined back into a string, forming the cleaned post.
def rem_dup_hashtags(post):
words = post.split()
uniq_words = []
for word in words:
if word.startswith('#') and word not in uniq_words:
uniq_words.append(word)
elif not word.startswith('#'):
uniq_words.append(word)
cleaned_post = ' '.join(uniq_words)
return cleaned_post
# Let's now call the func to remove duplicate tags from posts
if __name__ == "__main__":
user_post = "Enjoying a great day with #friends! #Friends forever. #Fun times ahead! #Friends"
cleaned_post = rem_dup_hashtags(user_post)
print("Main post:", user_post)
print("Post with duplicate hashtags removed:", cleaned_post)
7. Write an algo to find the top N influencers in a large Facebook community based on their post engagement metrics.
Answer:
The algo for finding the top N influencers in a large Facebook community will have the following key steps:
Firstly, the algo calculates an engagement metric for each post, considering factors like likes, comments, and shares. The calculation is happening within the calc
function.
Next, the algo utilizes a dictionary, named metrics
, to link these metrics with individual influencers. For each post, it updates or initializes the influencer’s metric in the dictionary.
The influencers are then sorted based on their cumulative metrics in descending order. This results in a list of tuples, top_influencers
, where each tuple contains the influencer’s name and their total engagement metrics.
Finally, the top N influencers are retrieved from the sorted list, forming the top_n
list.
def top_n_influencers(posts, n):
metrics = {}
for post in posts:
metric = calc(post)
author = post['author']
metrics[author] = metrics.get(author, 0) + metric
top_influencers = sorted(metrics.items(), key=lambda x: x[1], reverse=True)
top_n = top_influencers[:n]
return top_n
def calc(post):
# Placeholder for the engagement metric calculation
return post['engagement']
# Example usage
if __name__ == "__main__":
posts = [
{'author': 'Inf1', 'engage': 150},
{'author': 'Inf2', 'engage': 120},
{'author': 'Inf1', 'engage': 80},
# ... (more posts)
]
top_influencers = top_n_influencers(posts, 3)
print("Top 3 influencers based on post engagement:")
for influencer, metric in top_influencers:
print(f"{influencer}: {metric} engagement")
8. What is the purpose of the @property
decorator in Python?
Answer:
The @property
decorator is used to turn a method into a read-only property. It allows you to access a method as if it were an attribute without calling it explicitly.
# Example: Using @property
class MyClass:
def __init__(self):
self._value = 42
@property
def value(self):
return self._value
obj = MyClass()
print(obj.value)
Check This: Concatenate Strings in Python
9. How can you concatenate variables of different data types into a string in Python?
Answer:
We can use Python string formatting or the f-string
method. Here’s an example using f-strings:
name = "Ramashish"
age = 25
message = f"My name is {name} and I am {age} years old."
10. Write a Python function to reverse the words in a user’s Facebook post while keeping the order of punctuation marks.
Answer:
To efficiently reverse the words in a user’s Facebook post while preserving the order of punctuation marks, you can follow these steps:
- Split the post into words.
- For each word, reverse it if it contains only alphabetic chars (keeping the order of punctuation marks).
- Join the reversed words back into a string.
Also Check: Python Reverse a List
Now, here’s the Python code to achieve the goal:
def rev(post):
words = post.split()
rev_words = [w[::-1] if w.isalpha() else w for w in words]
rev_post = ' '.join(reversed_words)
return rev_post
# Let's call the rev() method
if __name__ == "__main__":
post1 = "Hello, world! Coding is fun."
post2 = rev_words(user_post)
print("The post before:", post1)
print("The post after:", post2)
Now, let’s proceed to Apple.
10 Apple Python Programming Interview Questions
In the Apple Python programming interview questions, discover topics ranging from utilizing the enumerate function and filtering Pandas DataFrames to organizing iPhone photos based on content categories. Learn to leverage pre-trained models for image classification and implement practical functions, showcasing proficiency in both data analysis and computer vision concepts.
1. How do you check if a key exists in a Python dictionary, and what happens if you try to access a non-existing key?
Answer:
We can use the in
keyword to check if a key exists in a dictionary. If we try to access a non-existing key, it will raise a KeyError
. Here’s an example:
my_dict = {'name': 'Siteshwar', 'age': 25}
# Check if a key exists
if 'name' in my_dict:
print(my_dict['name'])
# Try to access a non-existing key
try:
print(my_dict['city'])
except KeyError:
print("Key not found.")
2. What is the purpose of the __name__
variable in Python?
Answer:
The __name__
variable is a special variable in Python that is automatically set by the interpreter. It helps to determine whether a Python file will run as the main program or will act as a module.
# Example: Using __name__
if __name__ == "__main__":
print("This script is being run as the main program.")
3. How can you filter rows in a Pandas DataFrame where the ‘Score’ column is greater than 80?
Answer:
We can filter rows using boolean indexing:
df_filtered = df[df['Score'] > 80]
4. Create a Python function that identifies the most frequently used emojis in a collection of iMessages.
Answer:
To identify the most frequently used emojis in a collection of iMessages, we will create a Python function using the emoji
library to handle emoji extraction. Ensure you have the emoji
library installed before running the code:
Let’s now write the code to handle the messages.
import emoji
from collections import Counter
def most_frequent_emojis(imessages):
emojis = [c for m in imessages for c in m if c in emoji.UNICODE_EMOJI['en']]
emoji_counts = Counter(emojis)
return emoji_counts.most_common()
# Let's find the most used emoji
if __name__ == "__main__":
imessages = [
"Hey! 😊 How are you today? 🌞",
"I'm doing well, thanks! 😃",
"Let's catch up later. 🍕",
"Sure! 🎉",
# ... (more iMessages)
]
most_freq = most_frequent_emojis(imessages)
print("Most frequently used emojis:")
for emoji, count in most_freq:
print(f"{emoji}: {count} times")
This function iterates through the messages, extracts emojis, and then counts the occurrences using the Counter
class from the collections
module. The result is a list of tuples containing the most frequently used emojis and their counts. Adjust the imessages
list with your actual iMessages data for testing.
5. Create a Python function to categorize photos in a user’s iPhone library based on their content (e.g., people, landscapes, animals, food).
Answer:
To categorize photos in a user’s iPhone library based on their content, you can use a pre-trained image classification model. One popular library for this task is Pytorch with the torch vision module. Before running the code, you’ll need to install the required libraries:
pip install torch torchvision
Let’s now write the code to organize photos.
import torch
from torchvision import models, transforms as T
from PIL import Image
def cat_photos(photo_paths):
model = models.resnet18(pretrained=True).eval()
transform = T.Compose([T.Resize((224, 224)), T.ToTensor(),
T.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])])
cat = {} # Dict to store photo categories
for path in photo_paths:
img = Image.open(path).convert('RGB')
input_tensor = transform(img)
output = model(input_tensor.unsqueeze(0))
with open("imagenet_classes.txt", "r") as file:
labels = [line.strip() for line in file.readlines()]
_, idx = torch.max(output, 1)
label = labels[idx.item()]
cat.setdefault(label, []).append(path)
return cat
# Let's call the above func
if __name__ == "__main__":
photos = ["path/to/photo1.jpg", "path/to/photo2.jpg", "path/to/photo3.jpg"]
result = cat_photos(photos)
for cat, paths in result.items():
print(f"{cat.capitalize()}: {len(paths)} photos")
Note:
- The example uses a pre-trained ResNet-18 model, and you may need to fine-tune or choose a different model based on your specific needs.
- The ImageNet labels file (“imagenet_classes.txt”) is for reference purposes. You can replace it with your own categories or adjust it accordingly.
- Ensure to replace the example photo paths with the actual paths to your user’s photos.
6. Write a Python function that takes a Facebook post as input and returns a dictionary containing the frequency of each unique word in the post, excluding common stop words (e.g., “the”, “and”, “of”).
Answer:
We will use the nltk
library for the count and token filtering purposes. Please ensure the nltk
library installed before running the code:
import nltk
from nltk.corpus import stopwords
from collections import Counter
nltk.download('stopwords')
def get_freq_of_words(post):
# Get the words in the post
words = nltk.word_tokenize(post.lower()) # Convert to lowercase for case-insensitivity
# Remove stop words
stop_words = set(stopwords.words('english'))
words = [word for word in words if word.isalnum() and word not in stop_words]
# Count the frequency of each word
word_freq = Counter(words)
return dict(word_freq)
# Call the func get_freq_of_words
if __name__ == "__main__":
fb_post = "Hello world! How's your Python coding going on. #Startlearn #Ready"
result = get_freq_of_words(fb_post)
print("Word Frequency:")
for word, freq in result.items():
print(f"{word}: {freq} times")
Check This: Python Dictionary to DataFrame
7. How do you create a Pandas DataFrame from a dictionary?
Answer:
We can create a Pandas DataFrame from a dictionary using the pd.DataFrame()
constructor. Each key-value pair represents a column in the data frame.
Let’s take the below example:
import pandas as pd
data = {'Name': ['Alice', 'Bob', 'Charlie'], 'Age': [25, 30, 22]}
df = pd.DataFrame(data)
8. How do you group data in a Pandas DataFrame based on a specific column?
Answer:
We can use the groupby()
method in Pandas. The following line of code demonstrates this:
grouped_data = df.groupby('Category')
9. What is the difference between np.mean()
and np.average()
in NumPy?
Answer:np.mean()
calculates the arithmetic mean, while np.average()
allows you to specify weights for each value in the array.
import numpy as npy
# Create a NumPy array
arr = npy.array([0.1, 0.2, 0.3, 0.4, 0.5])
# Calculate the arithmetic mean using np.mean()
mean_result = npy.mean(arr)
print(f"Arithmetic Mean: {mean_result}")
# Calculate the weighted average using np.average() with weights
weights = npy.array([0.1, 0.2, 0.3, 0.2, 0.2])
wavg_result = npy.average(arr, weights=weights)
print(f"Weighted Average: {wavg_result}")
10. How do you remove duplicates from a list in Python?
Answer:
We can remove duplicates from a list using the list(set())
idiom:
main_list = [1, 2, 2, 3, 4, 4, 5]
unique_list = list(set(main_list))
In this example, the unique list will contain only the unique elements from the main.
Conclusion
With the above questions, we hope you get some help in your preparations. However, the mantra to succeed is to find more ideas and keep practicing.
Also, remember not to ignore the conceptual knowledge which is compulsory when it comes to one-to-one interviews with hiring managers. Ensure that you have a good grasp of the main programming concepts.
All the very best,
Team TechBeamers