behnam heidary behnam heidary - 1 year ago 87
Python Question

What does this for loop with undefined terms inside brackets mean in python?

I have a mathematics code in python and need to convert it to java. But I can't understand it:

#python source
sum([d**2 for d in (x - y)])

is not defined before this line.
are arrays and defined and have value. I have trouble with the
loop and the connexion with
in that loop.

Answer Source

The actual for loop surrounded by brackets is a list comprehension, which generates a list. This is expressed, in general, as follows:

[ expression( <variables> ) for <variables> in <list> ]

Which means your variables (here d) will iterate over the values in the given list (here (x - y)). The list returned will contain the value of the expression, evaluated for each value of d.

This way of writing defines the variable after it is used, so it is normal you haven't seen it defined before.

In clear, the code is equivalent to the following:

squares = []
for d in (x - y):

Trivially, sum returns the sum of the list.

Because you say your code is doing maths and you are saying arrays rather than lists, I will suppose from here on that you mean that x,y are numpy arrays.

In this case, x - y has a meaning: item by item subtraction of the arrays.
Written as a list comprehension, it would look like: [a - b for a,b inzip(x,y)]

Hence a python rewrite of that code could be:

sum = 0
for a,b in zip(x,y):
    sum += (a - b) * (a - b)

Or only with numpy functions:

numpy.square(x - y).sum()
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download