Search code examples
pythonlistinsert

Using bisect.insort to insert an item into a list, which is a part of a list of lists


I'm trying to manage a list of several lists and each one should be sorted at all times, but I can't insert items into each list separately.

I had a list of n lists

arr = [[]]*n

I was trying to use

bisect.insort(arr[b],c) 

to insert element c into b-th lsit while keeping it sorted, but it iserts c into every list in arr

Later on I discovered that regular incert works like that too if I use

arr[b].isert(idx,c)

Is there a possibility to change the structure of arr to continue using bisect.insort?


Solution

  • apparently when I do

    arr = [[]]*n 
    

    it creates a list of n references to one empty list. Instead I should have used

    arr = [[] for i in range(3)]