Data Structures Practice Questions
Practice Questions - Python 3 Data Collections
Practice Questions: Python 3 Data Collections
This practice guide is structured to reinforce the data collections concepts covered in Step 1: Data Structures Guide. Solving these exercises will help you develop collection indexing, mutable state adjustments, key-value mapping, set algebra logic, and string parsing skills.
Guidelines for Effective Learning:
- Solve Individually First: Attempt to write or trace out the logic for each task before reviewing the provided answers.
- Execute Locally: Run these blocks in your local terminal. Changing variables and monitoring the outputs is essential for programming mastery.
- Trace Complex Nested Structures: For dictionary-in-dictionary or list-in-list questions, map the outer index first before drilling down to inner elements.
Practice Questions Index
- Section 1: Lists (Questions 1-10) — Indexing, mutability, append/insert/pop, and slicing.
- Section 2: Tuples (Questions 11-20) — Unpacking, constant coordination, and immutability logic.
- Section 3: Sets (Questions 21-30) — Deduplication, membership checking, and set mathematics.
- Section 4: Dictionaries (Questions 31-40) — Key-value associations, safe retrieves, nested databases, and looping.
- Section 5: Strings (Questions 41-50) — Character sequences, formatting, case manipulations, and parsing.
1. Lists: Ordered Collections (Questions 1-10)
Question 1: Index-Based Access
Task: Create a list named schedule containing five core subjects. Print the first, third, and fifth elements using index markers.
Answer:
main.pyRunnableschedule = ["Physics", "English Lit", "Calculus", "World History", "Chemistry"] print("Period 1:", schedule[0]) print("Period 3:", schedule[2]) print("Period 5:", schedule[4])
Question 2: Modifying List State
Task: Take the list schedule from Question 1. Append the string "Physical Education" to the end, insert "Computer Science" at index 1, and remove the subject "Chemistry". Print the updated list.
Answer:
main.pyRunnableschedule = ["Physics", "English Lit", "Calculus", "World History", "Chemistry"] schedule.append("Physical Education") # Adds to end schedule.insert(1, "Computer Science") # Inserts at index 1 schedule.remove("Chemistry") # Removes first instance print("Updated Schedule:", schedule)
Question 3: Extracting Sub-Sequences (Slicing)
Task: Extract a sub-sequence list of the first three items and another sub-sequence containing the remaining items from the following schedule:
main.pyRunnableschedule = ["Physics", "Computer Science", "English Lit", "Calculus", "World History", "Physical Education"]
Answer:
main.pyRunnableschedule = ["Physics", "Computer Science", "English Lit", "Calculus", "World History", "Physical Education"] morning_courses = schedule[:3] afternoon_courses = schedule[3:] print("Morning Courses:", morning_courses) print("Afternoon Courses:", afternoon_courses)
Question 4: Searching and Counting Occurrences
Task: Retrieve the index location of "Calculus" from a schedule list, and count how many times "Study Hall" appears in the collection.
Answer:
main.pyRunnableschedule = ["Physics", "Study Hall", "Calculus", "World History", "Study Hall"] calculus_index = schedule.index("Calculus") study_hall_count = schedule.count("Study Hall") print("Calculus Index Position:", calculus_index) print("Study Hall Frequency:", study_hall_count)
Question 5: Numeric Array Sorting
Task: Sort a list of raw numeric test scores in ascending order, and then in descending order.
Answer:
main.pyRunnabletest_scores = [85, 92, 78, 96, 88] ## Ascending sort test_scores.sort() print("Ascending Sort:", test_scores) ## Descending sort test_scores.sort(reverse=True) print("Descending Sort:", test_scores)
Question 6: Merging and Replicating Lists
Task: Combine two lists, core_courses and elective_courses. Then, replicate a two-element task list chores three times in sequence.
Answer:
main.pyRunnablecore_courses = ["Physics", "Calculus"] elective_courses = ["Art", "Music"] combined_list = core_courses + elective_courses print("Merged Courses List:", combined_list) chores = ["Clean Desk", "Backup Server"] repeated_tasks = chores * 3 print("Replicated Task List:", repeated_tasks)
Question 7: Conditional List Extraction
Task: Given a list of numerical student scores, extract only those scores that are greater than or equal to 75 into a new list.
Answer:
main.pyRunnableall_scores = [65, 88, 72, 95, 54, 82] passing_scores = [score for score in all_scores if score >= 75] print("Passing Scores Array:", passing_scores)
Question 8: Accessing Nested Matrices (Grids)
Task: Retrieve the value sitting at Row 2, Column 3 from the following seated student matrix (zero-indexed):
main.pyRunnableclassroom_grid = [ ["Alice", "Bob", "Charlie"], # Row 1 (index 0) ["David", "Emma", "Frank"], # Row 2 (index 1) ["Grace", "Henry", "Ivy"] # Row 3 (index 2) ]
Answer:
main.pyRunnableclassroom_grid = [ ["Alice", "Bob", "Charlie"], ["David", "Emma", "Frank"], ["Grace", "Henry", "Ivy"] ] ## Row 2 is index 1, Column 3 is index 2 occupant = classroom_grid[1][2] print("Seated at Row 2, Seat 3:", occupant)
Question 9: List Statistics Calculations
Task: Compute the maximum, minimum, and average values from a list of numerical scores.
Answer:
main.pyRunnablescores = [85, 92, 78, 96, 88] highest_score = max(scores) lowest_score = min(scores) average_score = sum(scores) / len(scores) print(f"Max: {highest_score} | Min: {lowest_score} | Average: {average_score:.1f}")
Question 10: Dynamic Sequence Shifts
Task: Extract the last element of a list using pop() and insert it at the very beginning of the list (index 0).
Answer:
main.pyRunnablecourses = ["Physics", "English Lit", "Calculus", "World History", "Art"] last_element = courses.pop() # Removes and returns "Art" courses.insert(0, last_element) print("Shifted Sequence:", courses)
Section Checkup
2. Tuples: Fixed Records (Questions 11-20)
Question 11: Tuple Declaration and Access
Task: Create a tuple holding three constant integers representing a locker combination. Print the second integer.
Answer:
main.pyRunnablecombination = (42, 17, 8) print("Locker Combination Step 2:", combination[1])
Question 12: Immutability Resolution
Task: Explain what error is raised if you attempt to reassign student_record[1] = 4.0 in the following tuple, and write code that successfully creates a new tuple reflecting that update:
main.pyRunnablestudent_record = ("Alice Smith", 3.8)
Answer: Attempting to assign values directly to an index of a declared tuple raises a TypeError: 'tuple' object does not support item assignment. To resolve this, you must declare a new tuple combining the original name and the new GPA value:
main.pyRunnablestudent_record = ("Alice Smith", 3.8) ## Reconstruct a new tuple instead of modifying the old one updated_record = (student_record[0], 4.0) print("Updated Record Tuple:", updated_record)
Question 13: Unpacking Variables
Task: Unpack a three-element tuple storing demographic coordinates (Latitude, Longitude, and Altitude) into three distinct variables and print them.
Answer:
main.pyRunnablecoordinates = (37.7749, -122.4194, 25.5) latitude, longitude, altitude = coordinates print("Latitude:", latitude) print("Longitude:", longitude) print("Altitude:", altitude)
Question 14: Merging Constant Records
Task: Merge a student's basic registration profile tuple and their academic statistics tuple using concatenation.
Answer:
main.pyRunnableprofile = ("Vance", 16) stats = ("Grade 10", 3.90) full_profile = profile + stats print("Merged Profile Tuple:", full_profile)
Question 15: Single-Element Tuple Validation
Task: Write code showing the difference in data types between a parenthesized integer (2026) and a single-element tuple containing 2026.
Answer:
main.pyRunnable## Parenthesized expression with no comma compiles as an integer integer_value = (2026) print("Type without comma:", type(integer_value)) # Outputs: <class 'int'> ## Adding a trailing comma makes it a tuple tuple_value = (2026,) print("Type with comma:", type(tuple_value)) # Outputs: <class 'tuple'>
Question 16: Index and Count Checks
Task: Count the occurrences of "A" in a tuple of letter grades, and find the index location of the first "B" grade.
Answer:
main.pyRunnablegrades = ("A", "B", "A", "C", "A") a_frequency = grades.count("A") first_b_index = grades.index("B") print("Frequency of A:", a_frequency) print("Index of First B:", first_b_index)
Question 17: Sorting Immutable Structures
Task: Sort the numeric elements of a tuple by converting it to a list, executing a sort, and converting it back.
Answer:
main.pyRunnableraw_tuple = (88, 95, 74, 91) temp_list = list(raw_tuple) temp_list.sort() sorted_tuple = tuple(temp_list) print("Sorted Tuple:", sorted_tuple)
Question 18: Constant Tuple Keys
Task: Retrieve a value from a dictionary that uses coordinate tuples as keys representing physical rows and columns.
Answer:
main.pyRunnablegrid_assignments = { (1, 1): "ServerA", (1, 2): "ServerB", (2, 1): "ServerC" } ## Retrieve target occupying value at Row 1, Column 2 active_node = grid_assignments[(1, 2)] print("Occupant at (1,2):", active_node)
Question 19: Membership Checks
Task: Verify if the subject "Chemistry" is present inside a tuple of curriculum requirements using the in operator.
Answer:
main.pyRunnablerequirements = ("Algebra", "English Lit", "US History", "Chemistry") is_present = "Chemistry" in requirements print("Chemistry requirement exists:", is_present)
Question 20: Multidimensional Records
Task: Extract and print the grade value of the second student in the following nested tuple array:
main.pyRunnablegradebook = ( ("Alice", 95.0), ("Bob", 88.5), ("Charlie", 92.0) )
Answer:
main.pyRunnablegradebook = ( ("Alice", 95.0), ("Bob", 88.5), ("Charlie", 92.0) ) bob_grade = gradebook[1][1] print("Bob's Grade:", bob_grade)
Section Checkup
3. Sets: Unique Elements (Questions 21-30)
Question 21: Set Initialization
Task: Initialize a set storing unique club members. Demonstrate how duplicate elements passed during initialization are automatically filtered.
Answer:
main.pyRunnablechess_club = {"Alice", "Bob", "Alice", "Charlie"} ## Duplicate "Alice" is automatically filtered print("Unique Chess Club Set:", chess_club)
Question 22: Deduplicating Lists
Task: Take a list containing duplicate email strings and convert it to a Set to filter out all duplicates.
Answer:
main.pyRunnableraw_emails = ["admin@school.edu", "user@school.edu", "admin@school.edu"] unique_emails = set(raw_emails) print("Deduplicated Emails Set:", unique_emails)
Question 23: Set Modifiers
Task: Add "David" to an active club set, and safely discard "Carol" without raising an error if she is not present in the set.
Answer:
main.pyRunnabledrama_club = {"Alice", "Bob", "Carol"} drama_club.add("David") drama_club.discard("Carol") # discard does not raise error if element is missing print("Updated Drama Club Set:", drama_club)
Question 24: Common Elements (Intersection)
Task: Find the elements that exist in both a science club set and an art club set.
Answer:
main.pyRunnablescience = {"Alice", "Bob", "Charlie"} art = {"Bob", "David", "Emma"} common_students = science.intersection(art) # Or: science & art print("Students in both clubs:", common_students)
Question 25: All Unique Elements (Union)
Task: Combine two club sets to find all unique students participating in at least one activity.
Answer:
main.pyRunnablescience = {"Alice", "Bob", "Charlie"} art = {"Bob", "David", "Emma"} total_participants = science.union(art) # Or: science | art print("Unique participating students:", total_participants)
Question 26: Set Deductions (Difference)
Task: Find all students who are in the science club but are NOT in the art club.
Answer:
main.pyRunnablescience = {"Alice", "Bob", "Charlie"} art = {"Bob", "David", "Emma"} science_only = science.difference(art) # Or: science - art print("Science Club only:", science_only)
Question 27: Symmetric Difference
Task: Find all students who participate in exactly one club (excluding those who are in both).
Answer:
main.pyRunnablescience = {"Alice", "Bob", "Charlie"} art = {"Bob", "David", "Emma"} exclusive_students = science.symmetric_difference(art) # Or: science ^ art print("Students in exactly one club:", exclusive_students)
Question 28: Subsets and Supersets
Task: Check if a set of honors students is a subset of all registered students.
Answer:
main.pyRunnableregistered_students = {"Alice", "Bob", "Charlie", "David", "Emma"} honors_students = {"Alice", "Charlie"} is_subset = honors_students.issubset(registered_students) print("Honors subset of Registered:", is_subset)
Question 29: Disjoint Allocations
Task: Check if two sets, biology_class and geology_class, have completely zero overlapping elements (disjoint).
Answer:
main.pyRunnablebiology_class = {"Alice", "Bob"} geology_class = {"David", "Emma"} no_overlap = biology_class.isdisjoint(geology_class) print("Classes have zero overlapping students:", no_overlap)
Question 30: High-Speed Membership Testing
Task: Demonstrate a fast membership verification check on a set of allowed IP addresses.
Answer:
main.pyRunnableallowed_ips = {"192.168.1.1", "10.0.0.5", "172.16.2.20"} is_allowed = "192.168.1.1" in allowed_ips print("IP address verified:", is_allowed)
Section Checkup
4. Dictionaries: Key-Value Pairs (Questions 31-40)
Question 31: Creating and Querying Keys
Task: Create a dictionary containing student details: Name, Grade, and GPA. Query and print the GPA value.
Answer:
main.pyRunnablestudent_record = { "name": "Sarah Miller", "grade": "11th", "gpa": 3.92 } print("GPA Value:", student_record["gpa"])
Question 32: Adding and Updating Key Values
Task: Take the student_record from Question 31. Update the GPA value to 3.98 and add a new key "enrolled_courses" initialized as a list containing "Calculus".
Answer:
main.pyRunnablestudent_record = { "name": "Sarah Miller", "grade": "11th", "gpa": 3.92 } student_record["gpa"] = 3.98 student_record["enrolled_courses"] = ["Calculus"] print("Updated Record:", student_record)
Question 33: Extracting Dictionary Metadata
Task: Extract all keys and values separately from a dictionary tracking class averages as list structures. Print the first course and its corresponding class average using index references from the extracted lists.
Answer:
main.pyRunnableclass_averages = { "Calculus": 88, "Chemistry": 85, "English Lit": 91 } ## Extract list of keys and values directly courses = list(class_averages.keys()) scores = list(class_averages.values()) print("First Course Key:", courses[0]) print("First Course Score:", scores[0])
Question 34: Safe Retrieval Operations
Task: Use .get() to query a dictionary of course grades for "Physics", supplying a default fallback score of 0 if the key does not exist.
Answer:
main.pyRunnablereport_card = { "Calculus": 92, "Chemistry": 87 } ## "Physics" is not in the dictionary, so get() returns our fallback value of 0 physics_score = report_card.get("Physics", 0) print("Physics Grade:", physics_score)
Question 35: Deleting Keys
Task: Remove the key "Chemistry" from a dictionary of course scores using pop(), saving the value for later printing.
Answer:
main.pyRunnablegrades = { "Calculus": 92, "Chemistry": 87, "English Lit": 91 } removed_score = grades.pop("Chemistry") print("Remaining Grades:", grades) print("Deleted Score Value:", removed_score)
Question 36: Querying Multi-Dimensional Nested Dicts
Task: Access and print the email address of student "S002" from the following nested directory database:
main.pyRunnabledirectory = { "S001": {"name": "Alice", "email": "alice@school.edu"}, "S002": {"name": "Bob", "email": "bob@school.edu"} }
Answer:
main.pyRunnabledirectory = { "S001": {"name": "Alice", "email": "alice@school.edu"}, "S002": {"name": "Bob", "email": "bob@school.edu"} } bob_email = directory["S002"]["email"] print("S002 Email:", bob_email)
Question 37: Merging Dictionaries
Task: Merge a student's core details dictionary and their contact details dictionary.
Answer:
main.pyRunnablecore_profile = {"name": "Marcus", "grade": "10th"} contact_info = {"email": "marcus@school.edu", "phone": "555-0143"} core_profile.update(contact_info) print("Merged Profile Dictionary:", core_profile)
Question 38: Updating Dictionary State
Task: Take an inventory tracker dictionary. Add 5 units to "Laptops" and update "Monitors" to a constant value of 10. Print the updated inventory.
Answer:
main.pyRunnableinventory = { "Laptops": 12, "Monitors": 8, "Keyboards": 15 } inventory["Laptops"] += 5 inventory["Monitors"] = 10 print("Updated Inventory Levels:", inventory)
Question 39: Key Existence Verification
Task: Verify if the student ID "S108" exists inside a directory dictionary, outputting the result directly as a Boolean variable.
Answer:
main.pyRunnabledirectory = { "S101": "Alice", "S102": "Bob" } target_id = "S108" is_registered = target_id in directory print("Student registration status verified:", is_registered)
Question 40: Manual Value Adjustments
Task: Take a dictionary containing decimal ratios. Manually convert the ratios for both keys to whole percentage integers and update the dictionary.
Answer:
main.pyRunnableratios = { "Alice": 0.95, "Bob": 0.88 } ratios["Alice"] = int(ratios["Alice"] * 100) ratios["Bob"] = int(ratios["Bob"] * 100) print("Updated Percentage Scores:", ratios)
Section Checkup
5. Strings: Text Manipulation (Questions 41-50)
Question 41: Character Index Access
Task: Print the first and last characters of a text string variable named system_code.
Answer:
main.pyRunnablesystem_code = "PynexHost" first_char = system_code[0] last_char = system_code[-1] print(f"First Character: {first_char} | Last Character: {last_char}")
Question 42: Parsing Email Domains
Task: Slice a student email string to extract the username (everything before the @ symbol).
Answer:
main.pyRunnableemail_address = "marcus_vance@school.edu" ## Find index location of the separator symbol at_index = email_address.find("@") username = email_address[:at_index] print("Extracted Username:", username)
Question 43: Case Formatting
Task: Convert a raw mixed-case course string "iNTrOdUcTiOn tO cAlCuLuS" into lower, upper, and proper Title case formats.
Answer:
main.pyRunnableraw_string = "iNTrOdUcTiOn tO cAlCuLuS" print("Lower Case:", raw_string.lower()) print("Upper Case:", raw_string.upper()) print("Title Case:", raw_string.title())
Question 44: Sub-String Searching
Task: Verify if the word "database" exists inside an essay string using the in operator, and find its exact character starting index.
Answer:
main.pyRunnableessay = "Advanced network protocols and database systems are integrated." contains_word = "database" in essay start_index = essay.find("database") print("Word 'database' exists:", contains_word) print("Starts at index location:", start_index)
Question 45: Replacing Text Characters
Task: Fix a spelling typo in an announcement string by replacing all instances of "Tuesdy" with "Tuesday".
Answer:
main.pyRunnableannouncement = "The server maintenance scheduled for Tuesdy has been moved." fixed_text = announcement.replace("Tuesdy", "Tuesday") print("Corrected Announcement:", fixed_text)
Question 46: Parsing Comma-Separated Values
Task: Split a comma-separated string roster of student names into a Python list of individual elements.
Answer:
main.pyRunnableroster_data = "Alice,Bob,Charlie,David" roster_list = roster_data.split(",") print("Parsed Roster List:", roster_list)
Question 47: Merging Lists to Strings
Task: Merge a Python list of subject strings into a single formatted string separated by the connector " | ".
Answer:
main.pyRunnablesubjects = ["Calculus", "Physics", "Chemistry", "English Lit"] formatted_string = " | ".join(subjects) print("Formatted Output:", formatted_string)
Question 48: Character Class Validation
Task: Check if a student ID string contains purely numeric digits, and if a system username contains purely alphabetical characters.
Answer:
main.pyRunnablestudent_id = "89112" username = "MarcusVance" print("ID contains digits only:", student_id.isdigit()) print("Username contains alphabetical letters only:", username.isalpha())
Question 49: Output Alignment (f-strings)
Task: Construct a formatted report line using f-strings where the name is left-aligned to 10 characters, the subject is left-aligned to 12 characters, and the numeric grade is right-aligned to 5 characters with 1 decimal place.
Answer:
main.pyRunnablestudent_name = "Marcus" subject = "Chemistry" score = 88.5 report_line = f"Student: {student_name:<10} | Subject: {subject:<12} | Score: {score:>5.1f}%" print(report_line)
Question 50: Trimming White Space
Task: Clean up user form entry inputs by removing extra surrounding spaces and newline characters from a name entry.
Answer:
main.pyRunnableraw_entry = " Marcus Vance \n" clean_entry = raw_entry.strip() print(f"Original: '{raw_entry}'") print(f"Cleaned Name: '{clean_entry}'")
Congratulations! 🎓
You have completed all 50 procedural Data Structures practice questions! You are fully prepared to build applications using robust collections. Keep practicing and happy coding!
Finished this lesson?
Mark it complete to advance your curriculum progress.