Search code examples
pythonpython-3.xlistconditional-statementsindex-error

Python 3.9.1 iterate lst to pass to tst2


I want to read all the elements from a list, lst, check the value, change for a number and save in another list, lst2.

lst = ['a','b','c'] 
lst2 = []

for x in range(len(lst)): 
    if lst[x] == 'a': 
        lst2[x] == 1
    if lst[x] == 'b':
        lst2[x] == 2
    if lst[x] == 'c':
        lst2[x] == 3

print(lst2)

Error:

IndexError: list index out of range.

I already tried with while loop and I get the same message. Can I achieve this in other way?


Solution

  • You need to fill lst2 with some values in order for the subscription assignments to work:

    lst = ['a','b','c'] 
    lst2 = [None] * len(lst)
    
    for x in range(len(lst)): 
        if lst[x] == 'a': 
            lst2[x] = 1
        if lst[x] == 'b':
            lst2[x] = 2
        if lst[x] == 'c':
            lst2[x] = 3
    
    print(lst2)
    

    Where [None] * len(lst) returns [None, None, None].

    Of course, there's the list.append() method, which would be really handy if you can be sure that the values use will be added in consecutive indices.