Don't understand this python For loop

Question:

I’m working through a tutorial which includes this code:

for position, target in population_gen(population):
    pos = float(position)
    all_inputs.append([random.random(), pos * factor])
    all_targets.append([target])

I don’t fully understand how the for loop works. In particular: what is the loop iterating through exactly? I’m only familiar with simple examples like for i in mylist:. How can there be a function call on the right-hand side of in, and two things separated by a comma on the left-hand side?

Asked By: Mike

||

Answers:

Tuple unpacking.

for a, b in [(1, 2), (3, 4)]:
  print a
  print b
  print 'next!'

And the function is just a function.

The function population_gen is returning a list of tuples, which are unpacked automatically into variable names using this syntax.

So basically, you’re getting something like the following as return value from the function:

[("pos1", "target1"), ("pos2", "target2"), ]

Given this example, in the the for loop’s first iteration, the variables “position” and “target” will have the values:

position = "pos1"
target = "target1"

In second iteration:

position = "pos2"
target = "target2"
Answered By: Erik Forsberg

The function either returns a sequence or serves as something called a “generator:” it spits out successive elements in a sequence for the caller to iterate through. This question concerning the yield keyword has some thorough discussion of how these work.

As for the comma, since the function (apparently) returns a two-tuple, the comma-separated list of names is a convenient way to name individual elements of the tuple without having to unpack them yourself.

Answered By: plasticsaber

It’s called tuple unpacking. The population_gen (generator) function yields tuples containing exactly two elements. In python, you can assign several variables to tuples like this

a, b = (1, 2)

So in this for loop, you directly put the two tuple values from the current iteration item into your two variables position and target.

Answered By: Johannes Charra
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.