Mike Mike - 1 month ago 4x
Python Question

Don't understand this python For loop

I'm still a python newb, but I'm working through the Pyneurgen neural network tutorial, and I don't fully understand how the for loop used to create the input data works in this instance:

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

What is the loop iterating through exactly? I've not come across the use of the comma and a function in the loop before.

Thanks in advance for any help :)


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"