List.extend() is not working as expected in Python

Question:

I have a list queueand an iterator object neighbors whose elements I want to append to the list.

queue = [1]
neighbor = T.neighbors(1) #neighbor is a <dict_keyiterator at 0x16843d03368>
print(list(neighbor)) #Output: [2, 3]
queue.extend([n for n in neighbor])
print(queue)

Output:

[1]

Expected Output:

[1, 2, 3]

What is going wrong?

Asked By: Kshitiz

||

Answers:

You consumed the iterator already:

print(list(neighbor))

Take that line out.

Answered By: user2357112

You already exhaust the iterator neighbor when you use it in the list constructor for printing, so it becomes empty in the list comprehension in the next line.

Store the converted list in a variable so you can both print it and use it in the list comprehension:

queue = [1]
neighbor = T.neighbors(1) #neighbor is a <dict_keyiterator at 0x16843d03368>
neighbors = list(neighbor)
print(neighbors) #Output: [2, 3]
queue.extend([n for n in neighbors])
print(queue)
Answered By: blhsing
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.