1

I need to create and use n heaps, I am trying to use heapq and is trying to push elements into a list of lists, where each element is to be considered a seperate heap. But its behaving weirdly. I just wanna push the elements 6 and 7 into my 3rd heap. but its getting pushed into all my heaps. any way out of this??

>>> test
[[], [], [], []]
>>> 
>>> heappush(test[2],6)
>>> heappush(test[2],7)
>>> test
[[6, 7], [6, 7], [6, 7], [6, 7]]
3
  • possible duplicate of Python List Index Commented Apr 27, 2013 at 11:18
  • You should really show the code. Commented Apr 27, 2013 at 11:22
  • Thanks a lot, that was the issue Commented Apr 27, 2013 at 11:27

2 Answers 2

3

You seem to have created test something like this:

>>> from heapq import heappush
>>> test = [[]] * 4
>>>
>>> heappush(test[2],6)
>>> heappush(test[2],7)
>>> test
[[6, 7], [6, 7], [6, 7], [6, 7]]

This creates four references to the same list object. Use a list comprehension to make four distinct lists:

>>> test = [[] for _ in range(4)]
>>> heappush(test[2],6)
>>> heappush(test[2],7)
>>> test
[[], [], [6, 7], []]
Sign up to request clarification or add additional context in comments.

1 Comment

I love it how you must've answered this question at least 5 times in the past few days.
2

You are using the same heap instance for all the heaps. Are you perhaps doing something like this?

test = [ [] * 4]

You need to create four distinct heaps instead. Exactly how depends on what you are doing now.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.