Home > Mobile >  Why do the results vary for generator output when using list or a for loop
Why do the results vary for generator output when using list or a for loop

Time:11-30

Behaviour 1

code with join:

print (' '.join(str(list(random.randrange(100) for j in range(4)))))

output:

[ 8 2 ,   8 3 ,   1 2 ,   7 1 ]

What I expected was:

[82,83,12,71]

Observation:

I'm using the list() function as I need to evaluate the generator expression. I assume this is where I'm going wrong, should I not be using list() with generators?

Behaviour 2:

code: same code ( without list()) but wrapped around another for loop:

for _ in range(2**2):
    print (' '.join(str(random.randrange(100)) for i in range(4)))

output:

98 72 56 63
71 12 45 63
83 91 65 89
31 45 65 95

Observation:

Here I get the expected out put. But I don't understand why this would work vs Behaviour 1 with a list. My understanding was that both a for loop and a list can be used interchangeably to force the output from a generator. What am I missing in understanding the difference where str() is taking the whole number in behaviour 2 but treating the output as a sequence of characters for behaviour 1?

CodePudding user response:

Code #1 is joining the string representation of a list, placing a space between each character in that string representation. Code 2 is joining a list of string representations, separating each with a space.

  • Related