chandlersun
chandlersun

Reputation: 1

Can for loop be used as part of a function variable in Python?

I encountered a line of python code like this:

''.join(random.choice(string.ascii_lowercase + string.digits) for _ in range(8))

It's kind of confusing.. anyone know what it does?

Upvotes: -1

Views: 50

Answers (2)

miraculixx
miraculixx

Reputation: 10379

''.join(random.choice(string.ascii_lowercase + string.digits) for _ in range(8))

When you see an expression like this, the best is to take it apart, step by step.

  • '' is an empty string
  • .join(...) will join all characters (the ... part) and add it to the empty string
  • random.choice(...) will choose any character at random
  • string.ascii_lower + string_digits creates a string that contains all lower case characters and all digits
  • for _ in range(8) means this is done 8 times (technically, this is a generator expression)

As a result, the whole expression returns a random string of 8 characters, all lower case or digits.

To learn more about generator expressions, Dan Bader has a nice tutorial. If you're wondering how one comes up with an expression like this, the best is to study the Python documentation, the official tutorial is a good start.

Upvotes: 2

Arkleseisure
Arkleseisure

Reputation: 438

I tried this piece of code:

import random
import string

a = 'abcdefghijk'
print(a.join(random.choice(string.ascii_lowercase + string.digits) for _ in range(8)))

It gave me this output:

tabcdefghijk2abcdefghijk7abcdefghijktabcdefghijklabcdefghijkoabcdefghijkfabcdefghijk0

I believe it takes an input string and sticks it together 7 times with either a random lowercase letter or a random digit. (7 times because there is one on either end and there are therefore 8 joining digits).

Upvotes: 0

Related Questions