Python for loops are actually foreach loops. You could do
ref =[1,2,3,4]
obt =[0.5,1,1.5,5]
for i in range(len(ref)):
if (obt[i] <= ref[i]):
print ("all ok")
else:
print("error")
The range function will iterate through the numbers 0 to the length of your array, range(len(ref)) = [0,1,2,3]
, you can then use for which in Python is actually a foreach to grab these numbers.
The enumerate function will give you both the index and the value, so you can also do
ref =[1,2,3,4]
obt =[0.5,1,1.5,5]
for i,r in enumerate(ref):
if (obt[i] <= r):
print ("all ok")
else:
print("error")
The enumerate function gives back the index and ref[i]
, which is being stored in i and r. This example better shows how Python is behaving like a foreach loop and not a for loop.
The reason for the error
On the line i,j=0
, you have to give j a value as well, so you would do i,j=0,0
. Now what happens here is that 0,0
is that same thing as (0,0)
. It's a tuple. The tuple then has to be unpacked. When a tuple is unpacked the first variable, i, gets the first value 0. The second variable, j, gets the second value. And if there where more values in the tuple this would continue until every value in the tuple is unpacked to some variable.
Once this is fixed we can proceed to the next line. for i,j in obt,ref
. Once again, you will see the exact same error. This time python is expecting to iterate over something in the form of [(2 value tuple), (2 value tuple), (2 value tuple), (2 value tuple)]
.
The zip function can be used to create this structure, as has been suggested above, or if you prefer using the indexes in a for loop, you could use for i in range(len(ref))
to iterate over the list of indexes [0,1,2,3]
. This
only work if ref and obt are the same length, otherwise you have to use zip.
Both ways work, using zip, or the method I mentioned, it's up to you how you want to solve the problem. If one list is longer than the other, zip will truncate the longer lists. The itertools.zip_longest solution that Games Braniac mentioned will extend the shortest length list so that they are the same size, and then zips them up.