Skip to content Skip to sidebar Skip to footer

Iterating Over A List In Python Using For-loop

I have a question about iterating over a list in python. Let's say I have a list: row = ['1', '2', '3'] and want to convert its element to integers, so that: row = [1, 2, 3]. I kn

Solution 1:

When you do for i in row, i takes the values in row, i.e. '1', then '2', then '3'.

Those are strings, which are not valid as a list index. A list index should be an integer. When doing range(len(row)) you loop on integers up to the size of the list.

By the way, a better approach is:

for elt_id, elt inenumerate(list):
    # do stuff

Solution 2:

When you do

for i inrow:
    row[i] =int(row[int(i)]) 

i is the element in the array row. Therefore, i will be '1' then '2' then '3'.

But indexes have to be integers and i is a string so there will be an error.


If you do:

for i inrow:
    row[int(i)] =int(row[i]) 

It will still be an error because i is the integer of element in the array row. Therefore, i will be 1 then 2 then 3.

But row[3] will cause a IndexError because there are only 3 elements in the list and numbering starts from 0.


While in the other case(the first case), i becomes 0 then 1 then 2 which does not cause an error because row[2] is valid.


The reason is :

range() is 0-index based, meaning list indexes start at 0, not 1. eg. The syntax to access the first element of a list is mylist[0] . Therefore the last integer generated by range() is up to, but not including, stop .

Solution 3:

Here's an example from IDLE:

>>>row= ['1', '2', '3']
>>>for i inrow:
    row[i] =int(row[i])

Traceback (most recent calllast):
  File "<pyshell#3>", line 2, in<module>row[i] =int(row[i])
TypeError: list indices must be integers or slices, not str

The items being iterated over are not integers, and cannot be used as an index to the list.

The following will work for some of the time, but throw an IndexError at the end:

for i inrow:
    i2 =int(i)
    row[i2] = i2

Solution 4:

Given row = ['1', '2', '3'], each item inside row is a string, thus it can be easily printed:

for i in row:
    print(i)

However, in your second example you are trying to access row using a string. You need an integer to access values inside a list, and row is a list! (of strings, but a list still).

for i inrow:
    # row[i] =int(row[i])  -> this will throw an error
    row[int(i)] =int(row[int(i)]) # this will throw an error

Post a Comment for "Iterating Over A List In Python Using For-loop"