Why does a list of generators only return the elements of the last generator?

50
April 11, 2021, at 11:30 PM

I'm given an arbitrary list of objects (e.g. ['foo', 'bar']). My goal is to produce a list of equal size where every element in the result list is a generator that repeats the respective input element 5 times.

This is a big simplification of what I actually want to do, and I am aware that there are many ways in which to solve this task. However, I have stumbled upon some weird behavior in how I wanted to solve this that I can not explain.

Here is my solution to the above task:

my_iterators = [
    (element for _ in range(5))
    for element in ["foo", "bar"]
]
for my_iterator in my_iterators:
    print(list(my_iterator))

I now expected the output to be:

['foo', 'foo', 'foo', 'foo', 'foo']
['bar', 'bar', 'bar', 'bar', 'bar']

However, to my surprise it was instead:

['bar', 'bar', 'bar', 'bar', 'bar']
['bar', 'bar', 'bar', 'bar', 'bar']

Why is it that (element for _ in range(5)) seems to be an iterator over the last element in the input_list irregarding of what it actually is in the context of for element in ["foo", "bar"]? How would I need to adapt my code to produce what my original goal was?

READ ALSO
How to use elasticsearch rangequery to find values that are less than or equal to a number value in Java API

How to use elasticsearch rangequery to find values that are less than or equal to a number value in Java API

Hello I'm new to Elastic Search and I'm trying to build an elastic search query using Java APII have the following

70
How to save agora stream in Android?

How to save agora stream in Android?

I am using agora sdk for streamingI want to save the stream in agora cloud

68
can't receive response from OpenWeatherMap API at all

can't receive response from OpenWeatherMap API at all

I am new to backend programming and recently I've this problem that I cant receive any data from Open Map Weather API

31
How to center horizontal scrollbar?

How to center horizontal scrollbar?

How can I position the scrollbar in the center of the parent div like so?

90