The_Basset_Hound
The_Basset_Hound

Reputation: 185

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?

Upvotes: 0

Views: 81

Answers (4)

Michal Frystacky
Michal Frystacky

Reputation: 1468

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

What you are looking at is list comprehension, which consists of the following:

  1. An Input Sequence.
  2. A Variable representing members of the input sequence.
  3. An Optional Predicate expression.
  4. An Output Expression producing elements of the output list from members of the Input Sequence that satisfy the predicate.

More on this

So you can do things like this:

a_list = [1, ‘4’, 9, ‘a’, 0, 4]

ints = [ i for i in a_list if type(e) == types.IntType ]
# print ints
# [ 1, 9, 0, 4 ]

Python documentation

Upvotes: 1

olofom
olofom

Reputation: 6471

The if is a you point out just a more compact way of doing an if.

The compact for is called a list comprehension. The documentation describes it better than I do :)

As per your example alist = [x for x in range(3)] is the equivalent of

alist = []
for x in range(3):
    alist.append(x)

The list comprehension can be mixed with conditionals, as in this example where we'd get all numbers 0-9

alist = [x for x in range(10)]
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

if we only want every second number we can use modulo for each loop:

alist = [x for x in range(10) if x % 2]
# [1, 3, 5, 7, 9]

which would be equal to

alist = []
for x in range(10):
    if x % 2:
        alist.append(x)

Upvotes: 3

Luis Masuelli
Luis Masuelli

Reputation: 12333

Such for statement is intended as syntactic sugar to a greater for. These three constructions are almost equivalent:

mylist = []
for x in range(3):
    mylist.append(x)

mylist = list(x for x in range(3))

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

However the example with range(3) is useless without transforming x somehow, like:

mylist = [x*x for x in range(3)] # will produce [0, 1, 4]

Please see the docs. The construction inside list() call in my example is something different. Is called generator comprehension.

Upvotes: 3

Brendan Abel
Brendan Abel

Reputation: 37509

They're called list comprehensions. Python has examples in their documentation.

Upvotes: 0

Related Questions