Creating python list containing lists with random characters

Question:

i would like to know what the purpose of the asterisk "*" is in the following example.
The code creates a password with the common requirements (2 digits, 2 upper case, …).

What confuses me is why there is a need for the asterisk before the random keyword:

passlength = random.randint(10, 16)
password = [
    *random.choices(string.ascii_uppercase, k=2),
    *random.choices(string.digits, k=2),
    *random.choices(string.punctuation, k=2),
    *random.choices(string.ascii_letters +
                    string.digits +
                    string.punctuation, k=passlength - 6)
]

I tried removing them but the error is: "expected str instance, list found"

Asked By: Goryls

||

Answers:

The asteriks preceeds the list that arise as a result of calling random.choices(string.ascii_uppercase, k=2) not the random module. This asteriks serves as unpacking operator in that case.

If you would remove all asterikses from your code, you would have a list of lists. If you add asterikses, the lists’ values are unpacked and form the list password

Answered By: deonardo_licaprio
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.