The bisect Module

The bisect module provides functions to insert items in sorted sequences.

insort(sequence, item) inserts an item into the sequence, keeping it sorted. The sequence can be any mutable sequence object that implements _ _getitem_ _ and insert; Example 14-28 demonstrates.

Example 14-28. Using the bisect Module to Insert Items in an Ordered List
File: bisect-example-1.py

import bisect

list = [10, 20, 30]

bisect.insort(list, 25)
bisect.insort(list, 15)

print list

[10, 15, 20, 25, 30]

In Example 14-29, bisect(sequence, item) => index returns the index where the item should be inserted. The sequence is not modified.

Example 14-29. Using the bisect Module to Find Insertion Points
File: bisect-example-2.py

import bisect

list = [10, 20, 30]

print list
print bisect.bisect(list, 25)
print bisect.bisect(list, 15)

[10, 20, 30]
2
1

Core Modules

More Standard Modules

Threads and Processes

Data Representation

File Formats

Mail and News Message Processing

Network Protocols

Internationalization

Multimedia Modules

Data Storage

Tools and Utilities

Platform-Specific Modules

Implementation Support Modules

Other Modules

show all menu



Python Standard Library
Python Standard Library (Nutshell Handbooks) with
ISBN: 0596000960
EAN: 2147483647
Year: 2000
Pages: 252
Authors: Fredrik Lundh
Similar book on Amazon

Flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net