Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Don't understand this python For loop

Tags:

python

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])
    all_targets.append([target])`

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 :)

like image 877
Mike Avatar asked Sep 18 '11 18:09

Mike


People also ask

How do you learn for loops in Python?

A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string). This is less like the for keyword in other programming languages, and works more like an iterator method as found in other object-orientated programming languages.

What does a comma mean in a for loop Python?

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.

How do you use a for loop Python?

for loops are used when you have a block of code which you want to repeat a fixed number of times. The for-loop is always used in combination with an iterable object, like a list or a range. The Python for statement iterates over the members of a sequence in order, executing the block each time.


1 Answers

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"
like image 117
Erik Forsberg Avatar answered Oct 06 '22 18:10

Erik Forsberg