Remove '\n', ' ', etc elements from a list

list = [‘a’, ‘\n’, ‘b’, ’ ',‘c’]. How can I remove the special characters without replacement in python to get the output as:
list = [‘a’, ‘b’,‘c’].

The most preferred way to selectively pick elements to form another list is via list comprehension. You can find examples on how to select elements using if in the linked article.

Hello Prajna,

list2 = [list.pop(i) for i, v in enumerate(list) if v in ['\n']] 

.pop() delete an elment from a list
enumerate return a dict from a list with an index, and we use this index to search the element we want to delete.
then we search the element with a check if our element is present in the list of element we want to remove, here [’\n’]

Thank you, it worked.

@PJha @Pesko
The proposed solution is incorrect.
Just try

list = ['a', '\n', '\n']

It doesn’t work because you are deleting elements from the list, the index doesn’t correspond to the elements anymore.
Also, it is bad practice to use a list comprehension here, as you don’t use the resulting list at all!
If you want a solution with pop, You should go from right to left, like:

list1 = list("a\n\n")
for i in range(len(list1)-1, -1, -1):
    if list1[i] == '\n':
        list1.pop(i)
print(list1)

A more Pythonic way is -as suggested by @uranusjr as well- is a proper list comprehension:

list1 = list("aa\nbc\n\nd")
list2 = [v for v in list1 if v not in ["\n"]]
print(list2)

One final remark: avoid using the word list for a variable as you override the builtin list by that.

1 Like