Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why is Python list.remove() not working properly?

I have some lists of strings and I’m trying to find the most repeated value for each one of them. For doing so, I recreated a function whose input is the desired list; however, many of those lists contain the following element '\\N'. (two backlash and a capital N)

I don’t want to take into account that element when the function search for the most repeated value, so I thought about filtering out said element from the list first and then run the function.

I tried using

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

NewList=List.remove('\\N')

to no avail. In fact, it deletes the whole list as I get nothing in return, using len(NewList) prints an error saying that it has no length. I thought that the element may be at fault, but I tried removing another string from the List and the same thing happened.

What’s going on? is there a better way to filter out that element from the list?
Thank You

>Solution :

Each time you call list.remove, it removes one matching item from the list, and returns None.

>>> my_list = ['foo', '\\N', 'bar', '\\N', 'ola']
>>> my_list.remove('\\N')
>>> my_list
['foo', 'bar', '\\N', 'ola']
>>> my_list.remove('\\N')
>>> my_list
['foo', 'bar', 'ola']

If you want to create a new list rather than modifying the existing list, consider using a list comprehension:

>>> my_list = ['foo', '\\N', 'bar', '\\N', 'ola']
>>> new_list = [i for i in my_list if i != '\\N']
>>> new_list
['foo', 'bar', 'ola']
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading