[Solved] for loop returning unexpected values when squaring values


You iterate over the list by using for elem in testList, which yields elements of the list and not their indices.

>>> b = [1, 3, -4, 5, 5, 3, 2, 1, 4, 8, 9]
>>> for i in b:
        print i,


1 3 -4 5 5 3 2 1 4 8 9 # Whereas you expected 0 1 2 3 4 5 6 7 8 9 10

So, your code fetches the elements using the values as the indices and returns the square of those values. This is what happens –

>>> for index, val in enumerate(b): # enumerate yields an (index, value) tuple which gets unpacked.
        print '{0} : {1}*{1} = {2}'.format(index, val, val**2)


0 : 1*1 = 1
1 : 3*3 = 9
2 : -4*-4 = 16
3 : 5*5 = 25
4 : 5*5 = 25
5 : 3*3 = 9
6 : 2*2 = 4
7 : 1*1 = 1
8 : 4*4 = 16
9 : 8*8 = 64
10 : 9*9 = 81

Whereas in your initial code, the a list happens to be the indices you’re expecting which builds up the correct list as you observed.

Easier Solutions

You could use a list comprehension to build up your lists, like (No Need to multiply a number by itself if you’re looking for it’s square, just use the builtin exponentiation operator (**))

>>> [elem**2 for elem in a]
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
>>> [elem**2 for elem in b]
[1, 9, 16, 25, 25, 9, 4, 1, 16, 64, 81]

Or a solution using map.

>>> map(lambda x: x**2, a)
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
>>> map(lambda x: x**2, b)
[1, 9, 16, 25, 25, 9, 4, 1, 16, 64, 81]

1

solved for loop returning unexpected values when squaring values