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
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']