-1

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
MatsLindh
  • 49,529
  • 4
  • 53
  • 84
  • 1
    You are seriously over-complicating this. Why not just `question.split(',')`? – Tomerikoo Oct 25 '21 at 07:19
  • Does this answer your question? [How to loop over a python list using the index numbers? (duplicate)](https://stackoverflow.com/q/61439258/6045800) – Tomerikoo Oct 25 '21 at 07:22
  • TL;DR - when iterating over a list in Python, you get the elements. i.e. if you do `for item in x:` you just need to do `list.pop(item)`. If on the other hand you want to use indexes, you need to do `for i in range(len(x)):` and then `list.pop(x[i])` (which is really not necessary when you can use the first option) – Tomerikoo Oct 25 '21 at 07:24
  • I tried this as well but the output is still wrong, however the first method suggested works just fine – Georgi Rumenov Oct 25 '21 at 08:32

2 Answers2

1

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.

enzo
  • 9,861
  • 3
  • 15
  • 38
0

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)