On 07/02/18 11: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.
First up I'll say you are doing an awful lot of work that's not needed. As a result your solution is much more complex than is necessary. Remember that a string is just like a list of letters so you don't need to convert it to a list. Just use it as is. Also strings have lots of useful methods that you can use - hint: try reading about them in the Python documentation, you might find easier ways to do things. > 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) This line does nothing useful. > inputlist = list(inputdata) > print(inputlist) > a = len(inputdata) > print(a) Note that you converted to a list but you are taking the length of the original string. > print ('xxxxxxxxxxxxxxxx') > for b in range(0,a): > print(a) > a = a - 1 This is a terrible idea. Don't mess with the values to give to range in a loop. Bad things are likely to happen. Also note that Pythons for loops give you each item in the data, you don;t need to mess about with indexes. And if you do need indexes enumerate() is usually a better solution than using range. (range is great if you just want a list of numbers but its usually the wrong way to process a collection of any kind) However in this case you are not using a or b, just reducing the size of a in each iteration, while increasing the size of b such that they will meet in the middle. I'm pretty sure that's not what you want? > print(inputlist) > inputlist.remove(',') This removes the commas starting at the front of the list. So you remove 1 comma each time round the loop. But you go round the loop half as many times as there are characters in the string. What happens if there are less commas than that? You don't show us the error, (if you used an attachment it will have been stripped by the server). But if it was a ValueError then I suspect you hit the above scenario. > print(inputlist) Let me suggest a simpler algorithm in pseudo code. (WE don;t do your homework for you so you will need to translate the pseudocode into real Python yourself) inputstr = input() for char in inputstr: if char not a comma print char There is an even shorter way if you use the built in string methods. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos _______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor