Insert Multiple Values Into a Sorted List in Python

Insert multiple values into an already-sorted list while keeping it sorted using the bisect.insort function.

Easy Python 3.9+ Aug 9, 2026 Algorithms & data structures 14 views 0 copies

Python code

14 lines
Python 3.9+
import bisect

def insert_sorted(sorted_list, values):
    for value in values:
        bisect.insort(sorted_list, value)
    return sorted_list

if __name__ == "__main__":
    original = [1, 3, 5, 7, 9]
    new_values = [4, 6, 2, 8, 0]
    result = insert_sorted(original, new_values)
    print(f"Original: {original}")
    print(f"Inserted: {new_values}")
    print(f"Result: {result}")

Output

stdout
Original: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Inserted: [4, 6, 2, 8, 0]
Result: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

How it works

The bisect module provides insort which inserts an element into a list while maintaining sorted order. The loop calls insort for each value, and because insertion happens in place, the original list gets mutated. The function returns the same list object, so original and result refer to the same list after the function call.

Common mistakes

  • Forgetting that `bisect.insort` modifies the list in place, so the original list is changed.
  • Not realizing that `insort` is O(n) per insertion due to the list shifting, leading to O(n*m) overall for m insertions.
  • Using the function on a list that is not already sorted, which will produce incorrect order.

Variations

  1. Use `bisect.insort` with a key function in Python 3.10+ for complex objects.
  2. For large sets of values, consider using `sort()` after extending the list with all values at once for better performance.

Real-world use cases

  • Maintaining a leaderboard in a game where new scores arrive continuously and must stay sorted.
  • Inserting events into a time-sorted log while preserving chronological order.
  • Adding items to a sorted inventory list in an e-commerce system without re-sorting the whole list.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Algorithms & data structures

Related tutorials and quizzes for this topic.