Write a python program to insert an item in a sorted list in the appropriate position.
Added 2 weeks ago
Active
Viewed 32
Ans

# Function to insert an item into a sorted list
def insert_sorted(lst, item):
    # Loop through the list and find the correct position
    for i in range(len(lst)):
        if lst[i] > item:
            lst.insert(i, item)  # Insert item at the found position
            return lst
    lst.append(item)  # If item is greater than all elements, add it at the end
    return lst

# Example usage
sorted_list = [10, 20, 30, 40, 50]
item = 35

# Insert the item into the sorted list
inserted_list = insert_sorted(sorted_list, item)
print(f"List after inserting {item}: {inserted_list}")

Sample Output:
List after inserting 35: [10, 20, 30, 35, 40, 50]





Related Questions