mardi 23 février 2016

Python - Using "if" and "for" in variable assignment

I see this done everywhere, but I don't get how it works. I have searched everywhere online and can't find an explanation. If an answer is already here, forgive me.

People often use if and for when assigning variables, as in

x = 0 if val == "yes" else 1

which is equivalent to

if val == "yes":
  x = 0
else:
  x = 1

I have also seen people use for inside of lists and other things.

alist = [x for x in range(3)]

How does this work? Where can I use it?

Aucun commentaire:

Enregistrer un commentaire