[Tutor] can someone explain the reason for error

Alex Kleider akleider at sonic.net
Wed Feb 7 12:56:46 EST 2018


On 2018-02-07 03:58, vinod bhaskaran wrote:
> Hi, I am a beginner level programmer and in one assignment the question
> given is:to remove ',' from a list after getting a comma separated 
> input
> from console.
> 
> I gave the below (most print statements are for reference except the 
> last
> print statement). but i get the attached error. can someone explain why
> this error nd how to rectify?
> 
> inputdata = input ('Enter comma separated data \n')
> type(inputdata)
> inputlist = list(inputdata)
> print(inputlist)
> a = len(inputdata)
> print(a)
> print ('xxxxxxxxxxxxxxxx')
> for b in range(0,a):
>     print(a)
>     a = a - 1
>     print(inputlist)
>     inputlist.remove(',')
> print(inputlist)


The following might help you on your way:
Python 3.6.3 (default, Oct  6 2017, 08:44:35)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> s = "a,b,c,d"
>>> l = list(s)
>>> l
['a', ',', 'b', ',', 'c', ',', 'd']
>>> l2 = s.split()
>>> l2
['a,b,c,d']
>>> l3 = s.split(',')
>>> l3
['a', 'b', 'c', 'd']


When 'list()' is handed a string, it returns a list of all characters in 
the string; in your case many of them are commas.
The str method 'split' takes a string and  splits it into an array: by 
default it uses white space as the delimiter (your string has no white 
space so it is returned as the only member of the list) but this (the 
delimiter) can be set to what you want. In your case you want to split 
on the comma character.
For "extra bonus points" you might want to look at the csv (comma 
separated values) module- it might be helpful depending on your use 
case.


More information about the Tutor mailing list