List.extend() is not working as expected in Python
Question:
I have a list queue
and 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?
Answers:
You consumed the iterator already:
print(list(neighbor))
Take that line out.
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)
I have a list queue
and 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?
You consumed the iterator already:
print(list(neighbor))
Take that line out.
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)