-1

I saw a line of code to generate random string.

''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(N))

I am not sure what type of usage is this and I cannot find it in python doc.

I try

random.choice(string.ascii_uppercase + string.digits) for _ in range(N)

but it says there's a syntax error

dspjm
  • 5,473
  • 6
  • 41
  • 62

1 Answers1

1

It's a generator expression:

The semantics of a generator expression are equivalent to creating an anonymous generator function and calling it. For example:

g = (x**2 for x in range(10))
print g.next()

is equivalent to:

def __gen(exp):
    for x in exp:
        yield x**2
g = __gen(iter(range(10)))
print g.next()
jtbandes
  • 115,675
  • 35
  • 233
  • 266
  • 1
    And, notably, *generators* are *iterable*, like lists. So you can call [`str.join`](https://docs.python.org/2/library/stdtypes.html#str.join) on them just like on a list. – Jon Surrell Dec 17 '15 at 09:52