Home > Article > Backend Development > Why Does \"ar[i]\" Throw an IndexError in a \"for i in ar\" Loop?
In Python, when coding a for loop to sum values in a list, an IndexError may arise if you attempt to access elements using "ar[i]" where "i" represents the current element of the list.
The error occurs because "ar[i]" attempts to index into the list using the current element as the index. However, the current element is not the index itself but the value at that index. In the given code, you are attempting to use a value as an index, which is not permitted.
To resolve this error, modify the loop as follows:
for i in ar: theSum = theSum + i
Instead of indexing the list with "i", you directly add the current element represented by "i" to "theSum".
Alternatively, you can employ a range loop:
for i in range(len(ar)): theSum = theSum + ar[i]
"range(len(ar))" generates a range of valid indices for the list, and you can use "ar[i]" within this loop without encountering the error.
The above is the detailed content of Why Does \"ar[i]\" Throw an IndexError in a \"for i in ar\" Loop?. For more information, please follow other related articles on the PHP Chinese website!