Baba Nebiyev
Baba Nebiyev

Reputation: 1

IndexError: iterate string on for loop and place character by index

guys I'm beginner at the coding. I can't find answer anywhere where I do mistake. it turns IndexError: list assignment index out of range all the time.

a = 'banana' 
lis = ['_ '* len(a)]

for i,ch in enumerate(a):
        lis[i] = ch
print(lis)  

Upvotes: 0

Views: 26

Answers (1)

ShadowRanger
ShadowRanger

Reputation: 155506

lis = ['_ '* len(a)]

makes a one-element list containing a string 2*len(a) characters long. Thus, lis[i] for any i aside from 0 is invalid. Presumably you meant to do something like:

lis = ['_ '] * len(a)

which would make lis have the same length as a.

That said, the best solution for making a list of the characters in a is just:

lis = list(a)

str are iterables of their characters (length 1 strs themselves), and list's constructor can convert any iterable to a list, so that's the simplest solution, no need for enumerate, no need to presize a list and reassign elements in it at all.

Upvotes: 1

Related Questions