Bisect Insert in Python

Level 372 keystrokes

This inserts an element into a sorted list while maintaining order.

Python code

# bisect works on lists that are already sorted
1import bisect
2
# The list must be sorted for insort() to keep it in order
3nums = [1, 3, 5, 7, 9]
# insort() finds the position by binary search and inserts 4 between 3 and 5
4bisect.insort(nums, 4)
# Prints [1, 3, 4, 5, 7, 9]
5print(nums)

Output

[1, 3, 4, 5, 7, 9]
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this Python code and how often they appear.

  • ,× 5
  • (× 2
  • )× 2
  • .× 1
  • [× 1
  • ]× 1
  • =× 1

More Python examples at level 3

← Python typing practice