python-3.xbisect

Python bisect behaviour with lists


I've been playing with bisect and I'm confused with the following behaviour:

Input:

test = 1
print(test)

bisect.insort([test], 6)

Output:

1
1

If I change when I define test as a list, I get a different response:

Input:

test = [1]
print(test)

bisect.insort(test, 6)

Output:

[1]
[1, 6]

Why does it do this?


Solution

  • bisect.insort appears to work "in place" on whatever is passed to it. So, in the first example you pass it a list that is known only in the scope of the function [test] and it will insert into that list and make a list of [1, 6] but it does not return that result or modify the variable test--which is a good thing.