myartsev
myartsev

Reputation: 1232

What is the difference between insort_left and insort_right in bisect?

Why do both insort_left and insort_right exist; isn't it always the same result since the elements are equal?

>>> import bisect
>>> foo = [1,2,3]
>>> 
>>> bisect.insort_left(foo, 1)
>>> foo
[1, 1, 2, 3]
>>> 
>>> bisect.insort_right(foo, 1)
>>> foo
[1, 1, 1, 2, 3]

Upvotes: 6

Views: 745

Answers (2)

Tim Peters
Tim Peters

Reputation: 70602

For most purposes the results are indistinguishable, but there are cases where it can matter, particularly when using the optional key= argument.

Do you understand the difference between sorting algorithms that are, or aren't, guaranteed to be "stable"? If not, click the link ;-)

ys = []
for x in xs:
    bisect.insort_right(ys, x)

fills ys with a stable sort of xs entries, but using insort_left() instead would not.

Upvotes: 9

wjandrea
wjandrea

Reputation: 32987

Objects can be equivalent without being identical.

>>> bisect.insort_left(foo, 1.0)
>>> foo
[1.0, 1, 1, 1, 2, 3]
>>> 
>>> bisect.insort_right(foo, 1.0)
>>> foo
[1.0, 1, 1, 1, 1.0, 2, 3]

Upvotes: 11

Related Questions