M. Zare M. Zare - 4 months ago 17
Python Question

IndexError when creating squared list

Would you please consider the following code?

start_list = [5, 3, 1, 2, 4]
square_list = []
for i in start_list:
square_list.append(start_list[i]**2)
print square_list


This code was meant to iterate over start_list and append each number squared to square list. So the output is meant to be:

[25, 9, 1, 4, 16]


Instead, I get:

Traceback (most recent call last):
File "python", line 4, in <module>
IndexError: list index out of range

Answer

You are using the values of start_list as positions of elements in start_list. The looping statement

for i in start_list
    square_list.append(start_list[i]**2)
print square_list

gives all values in start_list and then searches for elements with those values as indexes in start_list as can be seen when using the statement start_list[i]. Instead, it should read:

for num in start_list:
    square_list.append(num**2)
print square_list
Comments