1

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?

Kshitiz
  • 3,431
  • 4
  • 14
  • 22

2 Answers2

4

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)
blhsing
  • 91,368
  • 6
  • 71
  • 106
3

You consumed the iterator already:

print(list(neighbor))

Take that line out.

user2357112
  • 260,549
  • 28
  • 431
  • 505