Lists help us store and manage multiple values in programming. But instead of just reading about them, the best way to learn lists is by solving real-world problems! In this article, we will explore interesting and tricky scenario-based questions that will help you think step by step and improve your problem-solving skills in Mojo. These challenges will make learning lists fun and practical, helping you understand how to use them in different situations.
Superhero Team Roster

The Justice Defenders team is making a new squad. One by one, members share their superhero names. Just as they finish, an urgent alert appears. To keep the team strong, the leader removes the last name. Now ready, they set off on their first mission. Write a Mojo program to take superhero names as input, store them in a list, remove the last name, and display the final team.
Test Case:
Input:
Enter number of superheroes: 3
Enter superhero 1: Captain America
Enter superhero 2: Iron Man
Enter superhero 3: Spider Man
Expected Output:
Final team after removing last hero:
Captain America
Iron Man
Explanation:
This program allows the user to input a list of superheroes and then removes the last entered superhero from the list before displaying the final team.
- The program first creates an empty list called
heroes
to store superhero names. It then asks the user how many superheroes they want to enter and saves this number innum_heroes
. - A loop runs for
num_heroes
times, where it takes a superhero name as input, stores it inhero
, and adds it toheroes
list. - After collecting names, the program gets the total count of superheroes using
heroes._len_()
and stores it inlength
. It then removes the last hero usingheroes.pop(length)
. - Finally, it prints the updated list by looping through
heroes
and displaying eachhero
usinghero._getitem_()
.
def main(): var heroes = List[String]() var num_heroes = Int(input("Enter number of superheroes: ")) for i in range(num_heroes): hero = input("Enter superhero {}: ".format(i + 1)) heroes.append(hero) var length: Int = heroes.__len__() heroes.pop(length) print("Final team after removing last hero:") for hero in heroes: print(hero.__getitem__())
Movie Watchlist

Alex is making a list of movies to watch. They add movie names one by one, excited to enjoy them later. After finishing, they check the list and decide to remove the last movie. Now, the final list is ready for a great movie night! Write a Mojo program to take movie names as input, store them in a list, remove the last one, and show the final list.
Test Case:
Input:
Enter number of movies: 3
Enter movie 1: Inception
Enter movie 2: Interstellar
Enter movie 3: Avatar
Expected Output:
Updated watchlist after removing last movie:
Inception
Interstellar
Explanation:
This Mojo program is designed to create a movie watchlist, collect movie titles from the user, and then remove the last added movie before displaying the updated list.
- It starts by defining an empty list called
watchlist
, then asks for the number of movies and stores it innum_movies
. - A loop runs
num_movies
times, taking each movie title as input, storing it inmovie
, and appending (adding) it towatchlist
. - Once all movie names are collected, the program determines the total number of movies using
watchlist._len_()
and assigns it tolength
. After that, it removes the last movie fromwatchlist
by callingwatchlist.pop(length)
. - Finally, it iterates through the
watchlist
and displays eachmovie
usingmovie._getitem_()
.
def main(): var watchlist = List[String]() var num_movies = Int(input("Enter number of movies: ")) for i in range(num_movies): movie = input("Enter movie {}: ".format(i + 1)) watchlist.append(movie) var length: Int = watchlist.__len__() watchlist.pop(length) print("Updated watchlist after removing last movie:") for movie in watchlist: print(movie.__getitem__())
To-Do List Management

Jessica is managing her daily tasks with a to-do list. From morning till evening, she keeps adding tasks—buy groceries, finish a report, call a friend. As the day goes on, she happily checks off completed tasks, removing them one by one. With each task gone, her list gets lighter, and by the end of the day, she smiles at the empty list, feeling accomplished and ready for a new day! Write a Mojo program for this scenario.
Test Case:
Input:
Enter number of tasks: 3
Enter task 1: Write email
Enter task 2: Go to gym
Enter task 3: Prepare lunch
Enter task to remove: Go to gym
Expected Output:
Updated to-do list: [‘Write email’, ‘Prepare lunch’]
Explanation:
This program allows the user to create a to-do list, then removes a specified task if it exists.
- First, the program creates an empty list called
tasks
to store the tasks. It then asks the user how many tasks they want to add and saves that number in thenum_tasks
variable. - A
for
loop runsnum_tasks
times, taking each task description as input, saving it intask
, and appending it totasks
. - Once all tasks are collected, the program determines the total count using
tasks._len_()
and assigns it tolength
. After that, it removes the last entry usingtasks.pop(length)
. - Finally, it iterates through
tasks
and prints eachremove_task
usingremove_task._getitem_()
.
def main(): var tasks = List[String]() var num_tasks = Int(input("Enter number of tasks: ")) for i in range(num_tasks): task = input("Enter task {}: ".format(i + 1)) tasks.append(task) var length: Int = tasks.__len__() tasks.pop(length) print("Updated to-do list:") for remove_task in tasks: print(remove_task.__getitem__())
Books Read Tracker

Lisa is keeping track of the books she’s read. Every time she finishes a book, she adds it to her list. But one day, she notices a mistake, a book she had never read is on the list! She quickly fixes it by removing the wrong book and adding the right one. Now her list is perfect, and she’s ready to keep reading more books! Write a Mojo program that lets Lisa add books to her list, find and fix mistakes by removing wrong entries, and display the updated list.
Test Case:
Input:
Enter number of books: 2
Enter book 1: Harry Potter
Enter book 2: Twilight
Enter the book to correct: Twilight
Enter the correct book name: The Hobbit
Expected Output:
Corrected books list:
Harry Potter
The Hobbit
Explanation:
This program is designed to create a book list, allow the user to correct a book name, and then display the updated list.
- It starts by defining an empty list called
books
, then asks for the number of books and stores this innum_books
. Afor
loop runsnum_books
times, taking each book title as input, storing it inbook
, and adding it tobooks
list. - After gathering the titles, the program asks for an incorrect book name (
incorrect_book
) and the corrected name(correct_book
). It then determines the size of the listbooks._len_()
and assigns it tolength
. - A loop runs through
books
, checking if any entry matchesincorrect_book
usingbooks._getitem_(i)
. If a match is found, it removes the incorrect entry withbooks.pop(i)
and replaces it withcorrect_book
usingbooks.insert(i, correct_book)
. - Finally, the program goes through
books
and prints eachshow_book
usingshow_book._getitem_()
.
def main(): var books = List[String]() var num_books = Int(input("Enter number of books: ")) for i in range(num_books): book = input("Enter book {}: ".format(i + 1)) books.append(book) var incorrect_book = input("Enter the book to correct: ") var correct_book = input("Enter the correct book name: ") var length: Int = books.__len__() for i in range(length): if books._getitem_(i) == incorrect_book: books.pop(i) books.insert(i, correct_book) print("Corrected books list:") for show_book in books: print(show_book.__getitem__())
Finding Your Favorite Color

Emma has a list of her favorite colors, like blue, pink, and green. One day, she wonders if a certain color is on the list. She decides to check. If the color is there, she’ll be happy. If not, maybe she’ll add it next time. It’s a simple way to see what she loves! Write a Mojo program that lets Emma check if a color is in her list of favorite colors.
Test Case:
Input:
Enter number of colors: 3
Enter color 1: Red
Enter color 2: Blue
Enter color 3: Green
Enter a color to check: Blue
Expected Output:
Yes, Blue is in your favorite colors.
Explanation:
This program is designed to create a favorite colors list, allow the user to check if a specific color is in the list, and then display the result.
- It starts by making an empty list called
favorite_colors
, then asks for the number of colors and saves this innum_colors
. - A loop runs
num_colors
times, taking each color name as input, storing it incolor
, and adding it tofavorite_colors
. - After collecting all colors, the program asks the user for a color to check (
check_color
). It then looks forcheck_color
infavorite_colors
. If the color is found, it prints a message confirming its presence. Otherwise, it displays a message saying the color is not in the list.
def main(): var favorite_colors = List[String]() var num_colors = Int(input("Enter number of colors: ")) for i in range(num_colors): color = input("Enter color {}: ".format(i + 1)) favorite_colors.append(color) var check_color = input("Enter a color to check: ") if check_color in favorite_colors: print("Yes, {} is in the list.".format(check_color)) else: print("No, {} is not in the list.".format(check_color))
Warehouse Item Weight Categorization

A warehouse stores items of different weights, the items are categorized based on their weight:
– Less than 10 kg → Light items
– Between 10 and 50 kg → Medium items
– More than 50 kg → Heavy items
Write the Mojo program to categorize the weights manually.
Test Case:
Input:
Enter item weights: 5 32 8 100 45 9 72
Expected Output:
Light items:
5
8
9
Medium items:
32
45
Heavy items:
100
72
Explanation:
This Mojo program is built to take a list of item weights, categorize them based on their size, and then display the sorted groups.
- It starts by creating an empty list called
weights
and then asks the user to enter item weights as a single input string(item_weights
). - The program uses a loop to go through each character of
item_weights
. If a space is found, it adds the current number toweights
and resetsnum
. Otherwise, it builds the number by converting characters to integers usingatol()
. Once the loop ends, it adds the last number toweights
. - Next, the program creates three lists:
light_items
,medium_items
, andheavy_items
. It then goes throughweights
one by one. If a weight is less than 10, it goes intolight_items
. If it’s between 10 and 50, it gets added tomedium_items
. If it’s more than 50, it is stored inheavy_items
. - Finally, the program displays each category of items by going through
light_items
,medium_items
, andheavy_items
, printing each weight one by one.
def main(): var weights = List[Int]() var item_weights = input("Enter item weights: ") var i = 0 var num = 0 while i < item_weights.__len__(): if item_weights.__getitem__(i) == " ": weights.append(num) num = 0 else: num = num * 10 + atol(item_weights._getitem_(i)) i += 1 weights.append(num) var light_items = List[Int]() var heavy_items = List[Int]() var medium_items = List[Int]() var j = 0 while j < weights.__len__(): if weights.__getitem__(j) < 10: light_items.append(weights.__getitem__(j)) elif weights.__getitem__(j) <= 50: medium_items.append(weights.__getitem__(j)) else: heavy_items.append(weights.__getitem__(j)) j += 1 print("Light items:") for light_item in light_items: print(light_item.__getitem__()) print("Medium items:") for medium_item in medium_items: print(medium_item.__getitem__()) print("Heavy items:") for heavy_item in heavy_items: print(heavy_item.__getitem__())
The Ultimate Race

The National Athletic Federation is organizing the Ultimate Sprint Championship where top runners from different regions compete in a 100-meter sprint. The event officials maintain a record of each runner’s finishing speed in km/h but due to a recording issue, the speeds are not sorted. Your task as a data analyst is to process the raw speed data and find the second-fastest speed manually without using sorting functions. The challenge is that the fastest runner will receive the gold medal, but officials need to determine the silver medalist(second-fastest runner) before announcing the results. Since the event has multiple participants, your program should efficiently determine the second-fastest speed without sorting the entire list.
Test Case:
Input:
Enter runner speeds: 33 28 41 39 36 44 40 38 42 45
Expected Output:
Second fastest speed:
44
Explanation:
- It begins by displaying a race title and then asks the user to input runner speeds as a single string (
runner_speeds
). An empty list calledspeeds
is created to store the numbers. - A loop moves through
runner_speeds
, checking each character. If a space is found, it adds the current number tospeeds
and resetsnum
. Otherwise, it builds the number by converting characters to integers usingatol()
. After the loop finishes, the last speed is added tospeeds
. - Next, two variables
max1
andmax2
are set to zero to track the fastest and second fastest speeds. Another loop goes throughspeeds
. If a speed is greater thanmax1
, the program updatesmax2
with the oldmax1
and setsmax1
to the new highest speed. If a speed is greater thanmax2
but not equal tomax1
, it updatesmax2
. - Finally, the program displays the second fastest speed.
def main(): print("The Ultimate Sprint Championship") var runner_speeds = input(("ENter runner speeds (in km/h) separated by spaces: ")) var speeds = List[Int]() var i = 0 var num = 0 while i < runner_speeds._len_(): if runner_speeds._getitem_(i) == " ": speeds.append(num) num = 0 else: num = num * 10 + atol(runner_speeds._getitem_(i)) i += 1 speeds.append(num) var max1 = 0 var max2 = 0 var j = 0 while j < speeds._len_(): if speeds._getitem_(j) > max1: max2 = max1 max1 = speeds._getitem_(j) elif speeds._getitem_(j) > max2 and speeds._getitem_(j) != max1: max2 = speeds._getitem_(j) j += 1 print("Second fastest speed:") print(max2)
Emergency Medical Supply Collection

A disaster relief team is setting up emergency medical stations after a massive flood. They receive two batches of supplies from different sources. The supplies arrive one by one, and the team needs to log each item into a final inventory list manually. Your task is to write a Mojo program that takes inputs one by one for two lists and combines them into one final inventory list while keeping the original order intact.
Test Case:
Input:
Enter number of items in batch 1: 3
Enter item 1: Bandages
Enter item 2: Painkillers
Enter item 3: Antiseptic
Enter number of items in batch 2: 3
Enter item 1: Gloves
Enter item 2: Gauze
Enter item 3: Scissors
Expected Output:
Final Emergency Medical Supply List:
Bandages
Painkillers
Antiseptic
Gloves
Gauze
Scissors
Explanation:
- The program starts by creating an empty list called
merged_list
and setting upbatches
to 2, meaning it will collect items in two rounds. - A loop begins with
batch
set to 1 and asks the user to enter the number of items in the current batch. - Then, another loop runs to take input for each item, which is added to
merged_list
. Once all items from one batch are collected, the program moves to the next batch. - After both batches are processed, the program displays the final list. A loop goes through
merged_list
and prints each item one by one.
def main(): var merged_list = List[String]() var batches = 2 var batch = 1 while batch <= batches: var num = Int(input("Enter number of items in batch {}: ".format(batch))) var i = 1 while i <= num: var item = input("Enter item {}: ".format(i)) merged_list.append(item) i += 1 batch += 1 print("Final Emergency Medical Supply List:") var i = 0 while i < merged_list.__len__(): print(merged_list.__getitem__(i)) i += 1
Tracking Student Exam Scores

The Elite Scholars Challenge is an annual prestigious academic competition where the brightest students from different schools compete. Each student’s final score is recorded manually as they complete the challenge. The competition organizers want a program that allows them to input scores one by one, store them, and then display:
1. All recorded scores
2. The highest score (Top Scholar)
3. The lowest score (Needs Improvement)
Test Case:
Input:
Enter number of students: 5
Enter score for student 1: 92
Enter score for student 2: 85
Enter score for student 3: 97
Enter score for student 4: 88
Enter score for student 5: 74
Expected Output:
Elite Scholars Scores:
92
85
97
88
74
Top Scholars Score: 97
Lowest Scholars Score: 74
Explanation:
- The program creates an empty list
scores
and asks the user to enter the number of students. It then sets up two variables,highest
andlowest
, with extreme values (-9999
and9999
) to keep track of the top and lowest scores. - A loop runs for each student, asking for their score and storing it in
scores
. If the new score is greater thanhighest
, it updateshighest
. Similarly, if it is lower thanlowest
, it updateslowest
. - Once all scores are collected, the program prints the full list of scores, followed by the highest and lowest scores in the class.
def main(): var scores = List[Int]() var num_students = Int(input("Enter number of students: ")) var i = 1 var highest = -9999 var lowest = 9999 while i <= num_students: var score = Int(input("Enter score for student{}: ".format(i))) scores.append(score) if score > highest: highest = score if score < lowest: lowest = score i += 1 print("Elite Scholars Scores: ") i = 0 while i < scores.__len__(): print(scores.__getitem__(i)) i += 1 print("Top Scholars Score: ", highest) print("Lowest Scholars Score: ", lowest)
The Time Capsule Sorting

A group of scientists is analyzing a time capsule containing artifacts from different years. However, due to a malfunctioning teleportation device, some artifacts got scattered out of order. The team needs to sort the artifacts in ascending order manually, so they can correctly document history. Since modern sorting techniques are not allowed, they must use basic swapping methods to arrange the artifacts. Write a mojo program to solve this problem.
Test Case:
Input:
Enter number of artifacts: 5
Enter artifact year 1: 2023
Enter artifact year 2: 1987
Enter artifact year 3: 2050
Enter artifact year 4: 1995
Enter artifact year 5: 1800
Expected Output:
Sorted artifacts: 1800 1987 1995 2023 2050
Explanation:
This Mojo program is designed to sort artifact years from oldest to newest.
- It starts by asking the user how many artifacts they have (
number_of_artifacts
). Then, it collects each artifact’s year and stores them inartifacts
. Once all years are entered, the program uses a sorting method (Bubble Sort) to arrange them in order. - The sorting works by repeatedly comparing two years at a time using
i
andj
. If the first year (artifacts[j]
) is greaterthan the next year (artifacts[j + 1]
), they swap places. This process keeps repeating until all the years are correctly arranged, with the oldest year at the beginning and the newest at the end. - Finally, the program prints the sorted
artifacts
, displaying the artifact years from the past to the present, making it easier to see history in order.
def main(): var number_of_artifacts = Int(input("Enter number of artifacts: ")) artifacts = List[Int]() for i in range(number_of_artifacts): var year = Int(input("Enter artifact year {}: ".format(i + 1))) artifacts.append(year) for i in range(number_of_artifacts - 1): for j in range(number_of_artifacts - i - 1): if artifacts[j] > artifacts[j + 1]: temp = artifacts[j] artifacts[j] = artifacts[j + 1] artifacts[j + 1] = temp print("Sorted artifacts:", end=" ") for i in range(number_of_artifacts): print(artifacts[i], end=" ") print()
The Lost Satellite Signals

A deep-space exploration mission has been disrupted due to signal loss from multiple satellites. The ground station receives signal strength values at regular intervals, but due to cosmic interference, some values are missing (marked as -1). Your task is to predict the missing values by replacing each -1 with the average of its nearest left and right valid values. If there’s only one valid neighbor, use that value. If both left and right are missing, replace them with 0.
Test Case:
Input:
Enter number of signals: 7
Enter signal strength 1: 85
Enter signal strength 2: -1
Enter signal strength 3: 90
Enter signal strength 4: -1
Enter signal strength 5: -1
Enter signal strength 6: 72
Enter signal strength 7: 88
Expected Output:
Processed signals: 85 87 90 90 81 72 88
Explanation:
This program is designed to process a list of signal strengths, where some signals might be missing (represented as -1
). The goal is to replace the missing values with the best possible estimates using neighboring signals.
- First, the program asks the user how many signals they want to enter (
number_of_signals
) and then stores these values in a list calledsignals
. After collecting all signals, it scans through the list to find missing signals (-1
). - When the program encounters a
-1
, it checks the values of the signals on its left (signals[i - 1]
) and right (signals[i + 1]
):- If both neighbors exist (i.e., are not
-1
), it replaces the missing value with their average ((left + right) // 2
). - If only the left neighbor exists, it copies that value.
- If only the right neighbor exists, it copies that value.
- If both neighbors are also missing, it replaces the signal with
0
.
- If both neighbors exist (i.e., are not
- Once all missing values are replaced, the program prints the updated
signals
list.
def main(): var number_of_signals = Int(input("Enter number of signals: ")) var signals = List[Int]() for i in range(number_of_signals): var signal = Int(input("Enter signal strength {}: ".format(i + 1))) signals.append(signal) for i in range(number_of_signals): if signals[i] == -1: var left = 0 if i > 0 and signals[i - 1] != -1: left = signals[i - 1] var right = 0 if i < number_of_signals - 1 and signals[i + 1] != -1: right = signals[i + 1] if left != 0 and right != 0: signals[i] = (left + right) // 2 elif left != 0: signals[i] = left elif right != 0: signals[i] = right else: signals[i] = 0 print("Processed signals:", end=" ") for i in range(number_of_signals): print(signals[i], end=" ") print()
Car Rental Management System

A car rental company needs a menu-driven system to manage their rental fleet. The system should allow the company to:
1. Add a new car to the rental fleet (car model and rental price per day).
2. Rent out a car (mark a car as rented).
3. Return a car (mark a car as available again).
4. Display available cars for rent. Exit the system.
The system should keep running until the company chooses to exit.
Test Case:
Input:
Enter your choice: 1
Enter car model: Toyota Corolla
Enter rental price per day: 50
Enter your choice: 1
Enter car model: Honda Civic
Enter rental price per day: 60
Enter your choice: 2
Enter car model to rent: Toyota Corolla
Enter your choice: 5
Expected Output:
Toyota Corolla added to the rental fleet.
Honda Civic added to the rental fleet.
Toyota Corolla has been rented out.
Exiting Car Rental Management System…
Explanation:
This code is a simple Car Rental Management System that lets users add cars, rent them out, return rented cars, and view available cars.
- The program uses three lists to store information about cars:
car_models
: Stores the names of the cars.rental_prices
: Stores the rental price per day for each car.rented_status
: Stores whether the car is rented (True
) or available (False
).
- The program repeatedly shows a menu with five options and asks the user to enter a
choice
:- Add a Car: The user enters the car model and rental price, and the car is added to the lists.
- Rent a Car: The user enters the car model they want to rent. If it exists and is available, it is marked as rented.
- Return a Car: The user enters a car model to return. If it was previously rented, it is marked as available.
- Display Available Cars: The program lists all cars that are not rented along with their rental price.
- Exit: The program stops running.
- If the user enters an invalid choice, an error message is displayed.
- If a user tries to rent a car that is already rented, they are notified that it is unavailable.
- If a user tries to return a car that wasn’t rented, they are informed.
- The program runs continuously inside a
while True
loop until the user chooses to exit (5). - It iterates over the car lists using a
for
loop to find and update car details. - It checks conditions to ensure valid operations, such as ensuring that a car is available before renting.
def main(): print("=== Car Rental Management System ===") var car_models = List[String]() var rental_prices = List[Int]() var rented_status = List[Bool]() while True: print("\n1. Add a car") print("2. Rent out a car") print("3. Return a car") print("4. Display available cars") print("5. Exit") choice = Int(input("Enter your choice: ")) if choice == 1: var model = input("Enter car model: ") var price = Int(input("Enter rental price per day: ")) car_models.append(model) rental_prices.append(price) rented_status.append(False) print("{} added to the rental fleet.".format(model)) elif choice == 2: var rent_model = input("Enter car model to rent: ") var found = False for i in range(car_models.__len__()): if car_models[i] == rent_model and not rented_status[i]: rented_status[i] = True found = True print("{} has been rented out.".format(rent_model)) break if not found: print("Car not available for rent!") elif choice == 3: var return_model = input("Enter car model to return: ") var found = False for i in range(car_models.__len__()): if car_models[i] == return_model and rented_status[i]: rented_status[i] = False found = True print("{} is now available for rent again.".format(return_model)) break if not found: print("Car not found or already available!") elif choice == 4: var available_cars = False print("Available cars: ") for i in range(car_models.__len__()): if not rented_status[i]: print("- {} (${} per day)".format(car_models[i], rental_prices[i])) available_cars = True if not available_cars: print("No cars available for rent.") elif choice == 5: print("Exiting Car Rental Management System...") break else: print("Invalid choice! Try again.")
Airport Security Check: Missing Item Detector

At a busy international airport, passengers pass through security checks where they place multiple items (wallet, phone, laptop, watch, etc.) in trays for scanning. However, due to misplacement or theft, some passengers may not receive all their items back.
Your task is to track each passenger’s items and determine which specific items are missing after retrieval.
Input Format:
1. Number of passengers
2. For each passenger:
– Enter the number of items they placed in the tray.
– Enter the names of these items one by one.
– Enter the number of items they received.
– Enter the names of received items one by one.
Test Case:
Input:
Enter number of passengers:2
Passenger 1 – Number of items placed: 4
Enter item 1: laptop
Enter item 2: phone
Enter item 3: wallet
Enter item 4: watch
Passenger 1 – Number of items received: 3
Enter received item 1: laptop
Enter received item 2: wallet
Enter received item 3: watch
Passenger 2 – Number of items placed: 5
Enter item 1: bag
Enter item 2: tablet
Enter item 3: headphones
Enter item 4: passport
Enter item 5: glasses
Passenger 2 – Number of items received: 4
Enter received item 1: bag
Enter received item 2: tablet
Enter received item 3: passport
Enter received item 4: glasses
Expected Output:
Passenger 1 is missing: Phone
Passenger 2 is missing: Headphones
Explanation:
The program helps passengers track missing items from their luggage by comparing what they placed and what they received.
- The program starts by asking for the total number of passengers (
num_passengers
). For each passenger, it takes input on how many items they originally placed (num_placed
) and stores those items in a list calledplaced_items
. - Similarly, it asks how many items they received (
num_received
) and stores them in another list,received_items
. After gathering these details, the program checks for missing items by iterating throughplaced_items
and comparing each item withreceived_items
. - If an item is not found in
received_items
, it is added to themissing_items
list. This is done using a nested loop, where the outer loop goes throughplaced_items
and the inner loop checks if each item exists inreceived_items
. - If an item is missing, the program prints a message indicating which items are missing for the respective passenger. If no items are missing, it confirms that the passenger has received all their belongings.
def main(): var num_passengers = Int(input("Enter number of passengers:")) for i in range(num_passengers): var num_placed = Int(input(("Passenger {} - Number of items placed: ".format(i + 1)))) var placed_items = List[String]() for j in range(num_placed): placed_items.append(input(("Enter item {}: ".format(j + 1)))) var num_received = Int(input("Passenger {} - Number of items received: ".format(i + 1))) var received_items = List[String]() for j in range(num_received): received_items.append(input("Enter received item {}: ".format(j + 1))) var missing_items = List[String]() for item in placed_items: found = False for received in received_items: if item.__getitem__() == received.__getitem__(): found = True break if not found: missing_items.append(item.__getitem__()) if missing_items: print("Passenger {} is missing: {}".format(i + 1, ", ".join(missing_items))) else: print("Passenger {} has received all items.".format(i + 1))
Train Seat Reservation Issue

A train has multiple passengers booking seats. Each passenger reserves a seat number before the journey. However, due to a system glitch, some reserved seats are not recorded properly when passengers board.
Your program should:
1. Record the total number of reservations made before the journey.
2. Record the actual occupied seats after passengers board.
3. Identify and display the missing reservations (seats that were reserved but are now missing from the system).
Test Case:
Input:
Enter number of reserved seats: 5
Enter reserved seat 1: 101
Enter reserved seat 2: 102
Enter reserved seat 3: 103
Enter reserved seat 4: 104
Enter reserved seat 5: 105
Enter number of occupied seats: 3
Enter occupied seat 1: 101
Enter occupied seat 2: 103
Enter occupied seat 3: 105
Expected Output:
Missing reservations: 102, 104
Explanation:
- The program starts by asking the user for the total number of reserved seats (
num_reserved
) and stores the seat numbers in the listreserved_seats
. It then asks for the number of occupied seats (num_occupied
) and stores them inoccupied_seats
. - To check if any reserved seats are unoccupied, the program iterates through each seat in
reserved_seats
and checks if it appears inoccupied_seats
. - This is done using a nested loop, where the outer loop goes through each
seat
inreserved_seats
, and the inner loop checks if it exists inoccupied_seats
. - If a seat is missing, it is added to
missing_seats
. Finally, if there are missing seats, the program prints out the list of reservations that were not occupied; otherwise, it confirms that all reserved seats have been taken correctly.
def main(): var num_reserved = Int(input("Enter number of reserved seats: ")) var reserved_seats = List[String]() for i in range(num_reserved): reserved_seats.append(input(("Enter reserved seat {}: ".format(i + 1)))) var num_occupied = Int(input(("Enter number of occupied seats: "))) var occupied_seats = List[String]() for i in range(num_occupied): occupied_seats.append(input("Enter occupied seat {}: ".format(i + 1))) var missing_seats = List[String]() for seat in reserved_seats: found = False for occupied in occupied_seats: if seat.__getitem__() == occupied.__getitem__(): found = True break if not found: missing_seats.append(seat.__getitem__()) if missing_seats: print("Missing reservations: ", ", ".join(missing_seats)) else: print("All reserved seats are occupied correctly.")
The Pizza Order Customization Challenge

A famous underground pizzeria is known for its secret ingredient policy. Customers order their pizzas normally, but the restaurant has a strange rule:
– Some toppings can’t be placed together due to “ingredient conflicts.”
– Some toppings appear as “hidden ingredients”—they show up in the order even if the customer didn’t ask for them!
– The chef must fix the order manually before making the pizza.
Your task is to:
1. Take the customer’s pizza order (list of toppings).
2. Check for any conflicting toppings and remove the invalid ones.
3. Check for hidden ingredients and add them if necessary.
4. Print the final corrected order.
Test Case:
Input:
Enter number of toppings: 6
Enter topping 1: Cheese
Enter topping 2: Pepperoni
Enter topping 3: Pineapple
Enter topping 4: Olives
Enter topping 5: Jalapenos
Enter topping 6: Mushrooms
Expected Output:
Conflicting toppings found! Removing: Pineapple, Jalapenos
Adding hidden ingredients: Extra Cheese, Garlic, Honey Drizzle
Final Order: Cheese, Pepperoni, Olives, Mushrooms, Extra Cheese, Garlic, Honey Drizzle
Explanation:
- It starts by asking the user for the number of toppings (
num_toppings
) and stores them in theorder
list. Then, it definesconflicts
as pairs of toppings that shouldn’t go together (e.g.,"Cheese"
and"Pineapple"
) andhidden_ingredients
as toppings that automatically add another ingredient (e.g.,"Pepperoni"
adds"Extra Cheese"
). - In Step 1, the program checks each conflict pair in
conflicts
. If both toppings are present inorder
, it removes the second topping in the pair to maintain balance. The removed items are printed. - In Step 2, the program scans
hidden_ingredients
. If a topping from the list is found inorder
, its hidden ingredient is added unless it’s already present. The newly added ingredients are displayed. - Finally, in Step 3, the program prints the final modified pizza order.
def main(): var num_toppings = Int(input(("Enter number of toppings: "))) var order = List[String]() for i in range(num_toppings): order.append(input("Enter topping {}: ".format(i + 1))) # Define conflicting toppings var conflicts = [ ("Cheese", "Pineapple"), ("Pepperoni", "Mushrooms"), ("Olives", "Jalapeños") ] # Define hidden ingredients var hidden_ingredients = [ ("Pepperoni", "Extra Cheese"), ("Mushrooms", "Garlic"), ("Pineapple", "Honey Drizzle") ] # Step 1: Remove Conflicting Toppings var to_remove = List[String]() for t1, t2 in conflicts: if t1 in order and t2 in order: to_remove.append(t2._getitem_()) # Always remove the second one for balance for item in to_remove: order.remove(item._getitem_()) if to_remove: print("Conflicting toppings found! Removing:", ", ".join(to_remove)) # Step 2: Add Hidden Ingredients var added = List[String]() for t, hidden in hidden_ingredients: if t in order and hidden not in order: order.append(hidden._getitem_()) added.append(hidden._getitem_()) if added: print("Adding hidden ingredients:", ", ".join(added)) # Step 3: Print final order print("Final Order:", ", ".join(order))
Learning lists in Mojo through real-life scenarios makes problem-solving more interesting and practical. By working on tricky challenges, you get better at handling data step by step and thinking through solutions carefully. These scenario-based questions help you understand lists deeply and improve your coding skills. The more you practice, the more confident you’ll become in solving complex problems with ease!