Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing empty elements from an array in Python

Tags:

python

arrays

io

with open("text.txt", 'r') as file:
    for line in file:
        line = line.rstrip('\n' + '').split(':')
        print(line)

I am having trouble trying to remove empty lists in the series of arrays that are being generated. I want to make every line an array in text.txt, so I would have the ability to accurately access each element individually, of each line.

The empty lists display themselves as [''] - as you can see by the fourth line, I've tried to explicitly strip them out. The empty elements were once filled with new line characters, these were successfully removed using .rstrip('\n').

Edit:

I have had a misconception with some terminology, the above is now updated. Essentially, I want to get rid of empty lists.

like image 226
codaamok Avatar asked Nov 09 '13 11:11

codaamok


People also ask

How do you remove an empty element from an array?

In order to remove empty elements from an array, filter() method is used. This method will return a new array with the elements that pass the condition of the callback function. array.

How do you remove null elements from a list in Python?

There are a several ways to remove null value from list in python. we will use filter(), join() and remove() functions to delete empty string from list.

How do I remove blank spaces from a list in Python?

strip() Python String strip() function will remove leading and trailing whitespaces. If you want to remove only leading or trailing spaces, use lstrip() or rstrip() function instead.


1 Answers

Since I can't see your exact line, its hard to give you a solution that matches your requirements perfectly, but if you want to get all the elements in a list that are not empty strings, then you can do this:

>>> l = ["ch", '', '', 'e', '', 'e', 'se']
>>> [var for var in l if var]
Out[4]: ['ch', 'e', 'e', 'se']

You may also use filter with None or bool:

>>> filter(None, l)
Out[5]: ['ch', 'e', 'e', 'se']
>>> filter(bool, l)
Out[6]: ['ch', 'e', 'e', 'se']

If you wish to get rid of lists with empty strings, then for your specific example you can do this:

with open("text.txt", 'r') as file:
    for line in file:
        line = line.rstrip('\n' + '').split(':')
        # If line is just empty
        if line != ['']:
            print line
like image 190
Games Brainiac Avatar answered Sep 30 '22 07:09

Games Brainiac