Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: What does "foo() for i in range(bar)" mean?

Tags:

python

What exactly does the following statement mean in Python?

randrange(10**10) for i in range(100)

I'm aware that randrange is a random number generator but cant really make out the effect of the statement.

like image 978
seeker Avatar asked May 09 '12 09:05

seeker


1 Answers

The way you posted it, it's a SyntaxError.
But I guess the statement is inside []. Then it's a list comprehension which creates a list containing 100 random numbers. It is equivalent to this code:

whatever = []
for i in range(100):
    whatever.append(randrange(10**10))

If the code was inside () instead of [] it would be a generator expression, i.e. an iterable whose items are not created immediately but on demand.

like image 60
ThiefMaster Avatar answered Sep 30 '22 17:09

ThiefMaster