0% found this document useful (0 votes)
1 views8 pages

Python Practice Questions

The document contains 100 Python practice questions specifically designed for data analysts, divided into two sections: 50 basic and 50 medium difficulty questions. Topics covered include basic data types, lists, dictionaries, strings, file handling, math and statistics, and object-oriented programming. Each question aims to enhance Python skills relevant to data analysis tasks.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views8 pages

Python Practice Questions

The document contains 100 Python practice questions specifically designed for data analysts, divided into two sections: 50 basic and 50 medium difficulty questions. Topics covered include basic data types, lists, dictionaries, strings, file handling, math and statistics, and object-oriented programming. Each question aims to enhance Python skills relevant to data analysis tasks.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

50 Python Practice Questions for Data

Analysts (Core Python Only)


🔢 Basic Data Types & Operations (1–8)
1.​ Write a function to check if a number is prime.
2.​ Given a list of numbers, return the sum, minimum, maximum, and average using only
built-in functions.
3.​ Convert a string like "1,2,3,4,5" into a list of integers.
4.​ Write a function to count the frequency of each character in a string.
5.​ Given a float, round it to N decimal places without using round().
6.​ Check if a given string is a palindrome.
7.​ Write a function that returns True if a number is a perfect square.
8.​ Convert temperatures from Celsius to Fahrenheit for a list of values using a list
comprehension.

📋 Lists & List Comprehensions (9–16)


9.​ Remove all duplicates from a list while preserving the original order.
10.​Flatten a nested list (e.g., [[1,2],[3,[4,5]]]) into a single list.
11.​Given two lists, return their intersection, union, and difference.
12.​Write a function to rotate a list by k positions to the right.
13.​Find the second largest element in a list without sorting.
14.​Group a list of numbers into even and odd using list comprehension.
15.​Write a function to chunk a list into sublists of size n.
16.​Merge two sorted lists into one sorted list without using sort().

📖 Dictionaries & Sets (17–23)


17.​Count the frequency of each word in a sentence and return the top 3 most common
words.
18.​Invert a dictionary (swap keys and values). Handle duplicate values gracefully.
19.​Merge two dictionaries; if keys overlap, sum their values.
20.​Given a list of dictionaries (records), sort them by a specific key.
21.​Write a function to find all keys in a dictionary whose values exceed a threshold.
22.​Use a set to find elements present in List A but not in List B.
23.​Given a dictionary of student scores, group students into:
●​ Pass (>= 50)
●​ Fail (< 50)

🔤 Strings & Text Processing (24–30)


24.​Write a function to count the number of vowels and consonants in a string.
25.​Given a sentence, return each word reversed while keeping the word order unchanged.
26.​Implement a simple Caesar Cipher encoder and decoder.
27.​Extract all numbers from a string like:​
"I scored 95 out of 100 in 3 subjects"
28.​Write a function to check if two strings are anagrams of each other.
29.​Capitalize the first letter of every word in a sentence without using .title().
30.​Given a list of strings, return only those that contain a specific substring.

🔁 Functions, Loops & Comprehensions (31–37)


31.​Write a recursive function to calculate the factorial of a number.
32.​Implement the Fibonacci sequence using:
●​ Recursion
●​ Iteration

Compare the outputs.

33.​Write a generator function that yields prime numbers up to n.


34.​Use map(), filter(), and reduce() to process a list of numbers.
35.​Write a decorator that logs the execution time of any function.
36.​Write a function using *args and **kwargs to build a summary report string.
37.​Implement a memoization decorator from scratch to cache expensive function calls.

📂 File Handling & Data Parsing (38–42)


38.​Read a CSV file manually (without Pandas) and parse it into a list of dictionaries.
39.​Write the results of a calculation to a .txt file, then read it back.
40.​Count the number of:
●​ Lines
●​ Words
●​ Characters

in a text file.

41.​Parse a JSON string and extract specific fields from nested data.
42.​Read a CSV file, find rows where a numeric column exceeds a threshold, and write the
filtered rows to a new CSV file.

🧮 Math & Statistics (Pure Python) (43–47)


43.​Compute the mean, median, and mode of a list of numbers from scratch.
44.​Write a function to calculate the standard deviation and variance without using any
external library.
45.​Implement linear interpolation between two data points.
46.​Write a function to find the percentile value (e.g., 25th, 75th percentile) of a list.
47.​Normalize a list of numbers to a 0–1 scale using Min-Max normalization.

🧩 OOP & Advanced Python (48–50)


48.​Create a DataRecord class that:
●​ Stores rows of data
●​ Supports adding new rows
●​ Has a method to print a summary (count, min, max, average) of a numeric field
49.​Implement a simple Stack and Queue class using a Python list, with:
●​ push() / pop() methods for Stack
●​ enqueue() / dequeue() methods for Queue
50.​Write a CSVReader class that:
●​ Reads a CSV file during initialization
●​ Stores data as a list of dictionaries
●​ Supports methods like:
○​ filter_by(column, value)
○​ sort_by(column)
○​ to_dict_list()​

50 Medium Python Practice Questions for
Data Analysts (Core Python Only)
🔢 Numbers & Math (1–8)
1.​ Write a function that takes a list of numbers and returns a dictionary with the following
keys:
○​ mean
○​ median
○​ mode
○​ range
2.​ Given a list of sales figures, calculate the month-over-month percentage change.
3.​ Write a function to find all outliers in a list using the IQR method:
○​ Values below Q1 - 1.5 × IQR
○​ Values above Q3 + 1.5 × IQR
4.​ Calculate the weighted average of a list of scores given their corresponding weights.
5.​ Write a function that takes a number and returns its digit frequency as a dictionary.
6.​ Given a list of prices, apply a tiered discount:
○​ Prices greater than 100 → 10% discount
○​ Prices greater than 500 → 20% discount
7.​ Return the discounted prices.
8.​ Write a function to compute:
○​ Cumulative sum
○​ Cumulative product
9.​ of a list without using any external library.
10.​Given a list of integers, return the running maximum at each position.

📋 Lists & Sorting (9–16)


9.​ Sort a list of tuples (name, score):
○​ First by score in descending order
○​ Then by name alphabetically
10.​Given a list of numbers, return a new list with each element replaced by its rank (1 =
highest).
11.​Write a function to find the most frequent element in a list. Handle ties by returning all
tied elements.
12.​Given a list of daily temperatures, find the longest streak of consecutive days above a
threshold.
13.​Write a function that takes a list and returns True if it contains any duplicates.
14.​Given a list of transactions (date, amount), return the date with the highest total amount.
15.​Implement a function to zip multiple lists of different lengths, filling missing values with
None.
16.​Given a list of numbers, split it into two lists:
●​ Values above the mean
●​ Values below the mean

📖 Dictionaries (17–23)
17.​Given a list of records (dictionaries), return a summary dictionary showing:
●​ Count
●​ Sum
●​ Average

of a numeric field grouped by a category field.

18.​Write a function to deep merge two nested dictionaries. Keys at all levels should merge
instead of overwrite.
19.​Given a dictionary of {product: [monthly_sales]}, return the product with the highest
average sales.
20.​Write a function to filter a dictionary and keep only keys whose values meet a condition.
21.​Given a list of dictionaries representing employees, return a dictionary of:​
{department: [list_of_employee_names]}
22.​Write a function that takes a flat dictionary and nests it based on a delimiter in the key.​
Example:​
"a.b.c" → {"a": {"b": {"c": value}}}
23.​Given a dictionary of {student: scores_list}, return a dictionary of {student: grade} based
on average score (A/B/C/F).

🔤 Strings & Text Processing (24–30)


24.​Write a function to parse a key=value formatted string (similar to a config file) into a
dictionary.
25.​Given a list of email addresses, validate each one using basic string checks:
●​ Contains @
●​ Has a valid domain
●​ Proper structure

Return a dictionary of:


{email: valid_or_invalid}

26.​Write a function to truncate a string to a maximum length while always cutting at a word
boundary (not mid-word).
27.​Given a list of product names with inconsistent casing and extra spaces, clean and
standardize them.
28.​Extract all dates in the following formats from a paragraph of text:
●​ DD-MM-YYYY
●​ DD/MM/YYYY
29.​Write a function that takes a sentence and returns a dictionary of:​
{word: count}​
sorted by count in descending order.
30.​Given a string with mixed numbers and words, write a function to separate and return
them in two different lists.

📅 Dates & Time (31–35)


31.​Without using datetime math shortcuts, calculate the number of days between two dates
given as strings:​
"YYYY-MM-DD"
32.​Given a list of timestamps as strings:
●​ Sort them chronologically
●​ Find the largest gap between consecutive timestamps
33.​Write a function that groups a list of (date, value) tuples by week number and returns the
weekly totals.
34.​Given a list of dates, return which ones fall on:
●​ Weekdays
●​ Weekends
35.​Write a function to generate a list of all dates between a start and end date (inclusive).

🔁 Functions & Logic (36–42)


36.​Write a function that accepts:
●​ A list of dictionaries
●​ A list of column names

and returns only those columns (similar to SQL SELECT).

37.​Implement a groupby(data, key) function that groups a list of dictionaries by a given key
and returns a dictionary of lists.
38.​Write a function that applies a list of filter conditions (as lambda functions) to a dataset
and returns matching rows.
39.​Create a moving_average(data, window) function that returns the moving average for
each position using a sliding window.
40.​Write a function:​
top_n(data, key, n)​
that returns the top N records from a list of dictionaries based on a numeric field.
41.​Implement a simple search function that accepts a keyword and searches a list of
dictionaries across all string fields.
42.​Write a function that takes a list of dictionaries and detects missing values (None or
empty string), returning a report of:​
{field: missing_count}

📂 File Handling (43–46)


43.​Read a CSV file manually and compute the column-level summary:
●​ Count
●​ Null values
●​ Minimum
●​ Maximum
●​ Mean (for numeric columns)

Print the final report.

44.​Write a script that reads a folder of .txt files and produces a word frequency report
across all files combined.
45.​Read a JSON file containing a list of records, filter records based on a condition, and
write the filtered output to a new JSON file.
46.​Write a function that compares two CSV files with the same structure and outputs rows
that are different between them.

🧩 Real-World Analyst Scenarios (47–50)


47.​Given a list of (product, region, sales) tuples, write a function to produce a
cross-tabulation (product vs region matrix of sales totals) using only dictionaries.
48.​You have a list of customer transactions:​
{customer_id, date, amount}​
Write a function to identify customers who have made purchases in 3 or more
consecutive months.
49.​Given a dataset of:​
{employee, department, salary}​
compute the salary percentile rank of each employee within their department.
50.​Write a function that takes a list of (timestamp, event_type) tuples and calculates the
average time between events for each event type.

You might also like