Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating over a list in python using for-loop [duplicate]

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 know I can do it with list comprehension:

row = [int(i) for i in row]

or for-loop:

for i in range(len(row)):
    row[i] = int(row[i])

My question concerns range(len(row)) part. Can someone answer in layman friendly way, why I can do something like this:

for i in row:
    print(i)

But I can't do this:

for i in row:
    row[i] = int(row[i])
like image 262
mykoza Avatar asked Jun 28 '26 08:06

mykoza


2 Answers

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 in enumerate(list):
    # do stuff
like image 93
Mathieu Avatar answered Jun 30 '26 21:06

Mathieu


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 in row:
    # row[i] = int(row[i])  -> this will throw an error
    row[int(i)] = int(row[int(i)]) # this will throw an error
like image 29
ibarrond Avatar answered Jun 30 '26 23:06

ibarrond