Home > Net >  Simple list program doesn't work - list index out of range error
Simple list program doesn't work - list index out of range error

Time:10-25

Ok so the working of this program is very simple, by using the input function called question I want to divide every character of what the user enters into an individual string that is then placed in a list, e.g. if the user enters: a,b,c i want the output to be stored in a list such as this list = ["a", ",", "b", ",", "c"] then by using a for loop I want the index of every comma in the list to be found and thus removed, leaving only this as an output: list = ["a", "b", "c"]. What am I doing wrong?

question =input(">")

def split(question):
    return [char for char in question]


list = split(question)
print(list)

comma_index_ask = [i for i in range(len(list)) if list[i] == ","]
print(comma_index_ask)

for item in comma_index_ask:
    list.pop(comma_index_ask[item])

print(list)

OUTPUT:

>a,b,c
['a', ',', 'b', ',', 'c']
Traceback (most recent call last):
  File "C:main.py", line 14, in <module>
    list.pop(comma_index_ask[item])
IndexError: list index out of range

CodePudding user response:

This is what's happening when you run your code:

list = ['a', ',', 'b', ',', 'c']
comma_index_ask = [1, 3]

item = 1
list.pop(comma_index_ask[1])    # comma_index_ask[1]: 3
list.pop(3)                     # list: ['a', ',', 'b', 'c']

item = 3               
list.pop(comma_index_ask[3])    # comma_index_ask[3]: ???

To filter list, use a list comprehension:

list = [char for char in list if char != ',']

Also, don't name your variable list, it'll shadow the list built-in.

CodePudding user response:

There are many different ways to do this. Here's just one of them:

mystring = 'a,b,c'
comma_list = []
p = 0
while (p := mystring.find(',', p)) >= 0:
    comma_list.append(p)
    p  = 1
print(comma_list)
outlist = [c for c in mystring if c != ',']
print(outlist)
  • Related