3

I have a list which contains an item '\n' in it. I want to remove it. however, the remove command is not working for it. Can anyone tell me what I am doing wrong?

def main():
    list1 = ['\ng,g\ng,g,g\n', '\n', '\ns\ns,s\n', '\nd,d\nd\nd,d,d,d\n\n']
    print list1

    print list1.remove('\n')


if __name__ == '__main__':
    main()

Also, if my list were to contain many such entries '\n', how do I remove them all? I currently use set() to get the duplicates and then am trying to get the remove command to work. However, the set() command seems to change the sorting of the list. I'd rather iterate through the list and incase a '\n' is found, remove it.

Rishav Sharan
  • 2,763
  • 8
  • 39
  • 55
  • just to add; when i try to search for all elements which are '\n', my code again doesn't works. `list1 = ['\ng,g\ng,g,g\n', '\n', '\ns\ns,s\n', '\nd,d\nd\nd,d,d,d\n\n'] print list1 for xx in list1: if xx == '\n': print xx` – Rishav Sharan Sep 08 '11 at 11:12

5 Answers5

6

The remove method modifies the list in-place and returns None. Thus, when you use print list1.remove('\n'), the list is modified, but None is printed. Do it in two steps, instead:

list1.remove('\n')
print list1

To remove all occurrences, most natural would be to construct a new list while excluding the newlines. For example:

list2 = [a for a in list1 if a != '\n']

If it must be in-place for some reason, then repeatedly use list1.remove until an exception is raised:

while True:
    try:
        list1.remove('\n')
    except ValueError:
        break
Michael J. Barber
  • 24,518
  • 9
  • 68
  • 88
  • Thanks. can't believe i wasted so much time on such a tiny mistake. I was thinking that it was because of '\n' being a whitespace and was right now going through the regex tutorials. -_- – Rishav Sharan Sep 08 '11 at 11:51
5

this will remove all of them:

list1=filter(lambda x: x != '\n', list1)
Karoly Horvath
  • 94,607
  • 11
  • 117
  • 176
3

Removing stuff from a list is one of the many uses of list comprehensions:

no_n = [x for x in list1 if x != '\n']
# to change the original list
list1[:] = no_n
Jochen Ritzel
  • 104,512
  • 31
  • 200
  • 194
0

It works here:

def main():
    list1 = ['\ng,g\ng,g,g\n', '\n', '\ns\ns,s\n', '\nd,d\nd\nd,d,d,d\n\n']
    print list1
    list1.remove('\n')
    print list1


if __name__ == '__main__':
    main()

Try it here: http://codepad.org/YXHOHgwv

Arnaud Le Blanc
  • 98,321
  • 23
  • 206
  • 194
0
list1 = ['\ng,g\ng,g,g\n', '\n', '\ns\ns,s\n', '\nd,d\nd\nd,d,d,d\n\n']
list2 = []

list2 = [el.replace('\n', '') for el in list1]

print list2
   >>> 
['g,gg,g,g', '', 'ss,s', 'd,ddd,d,d,d']
develerx
  • 600
  • 5
  • 13