Geek Logbook

Tech sea log book

Inserting a Student into a Sorted List in Python

When working with sorted lists in Python, it’s essential to ensure that any new elements are added in the correct order.

Problem Statement

You have a list of student names sorted in alphabetical order, like this:

students = [
    'Alice Anderson',
    'Bob Brown',
    'Charlie Clark',
    'Diana Davis',
    'Eve Evans',
    'Frank Foster',
    'Grace Green'
]

You need to define a function add_student(sorted_list, new_student) that receives a list of names in the format above and a new student name. The function should insert the new student into the list in the correct position, maintaining the alphabetical order.

Solution

To solve this problem, we’ll create a function add_student that takes two arguments: the sorted list of student names and the new student name. The function will iterate through the list and insert the new student at the appropriate position. If the new student is greater than all current students, it will be added to the end of the list.

Here’s the code:

def add_student(sorted_list, new_student):
    new_list = []
    added = False
    for current in sorted_list:
        if not added and current > new_student:
            new_list.append(new_student)
            added = True
        new_list.append(current)
    if not added:
        new_list.append(new_student)
    return new_list

# Example usage
students = [
    'Alice Anderson',
    'Bob Brown',
    'Charlie Clark',
    'Diana Davis',
    'Eve Evans',
    'Frank Foster',
    'Grace Green'
]

new_student = 'Brian Black'
updated_list = add_student(students, new_student)
print(updated_list)

Explanation

  1. Initialize a New List and a Flag: We start by creating an empty list new_list to store the updated list of student names. We also initialize a boolean flag added to False. This flag will help us determine when the new student has been added.
  2. Iterate Through the Original List: We loop through each name in the original list. For each name (current), we check if the new student should be inserted before the current name.
  3. Insert the New Student in the Correct Position:
    • If the new student has not been added yet (not added) and the current name (current) is greater than the new student, we add the new student to the list and set the flag added to True.
    • We then add the current name to the new list.
  4. Handle the Case Where the New Student is the Greatest: After the loop, if the new student has not been added (meaning it is greater than all the names in the list), we append it to the end of the new list.
  5. Return the Updated List: Finally, we return the updated list of student names.

Conclusion

With this approach, you can ensure that a new student is inserted into the correct position in a sorted list. This method maintains the alphabetical order of the list, ensuring that the list remains sorted after adding the new student.

Tags: