-1

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?

Red
  • 26,798
  • 7
  • 36
  • 58

1 Answers1

0

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.

Red
  • 26,798
  • 7
  • 36
  • 58