[Tutor] Removing Null Elements from a List
Daniel Yoo
dyoo@hkn.eecs.berkeley.edu
Sat, 10 Mar 2001 06:29:19 -0800 (PST)
On Fri, 9 Mar 2001, Britt Green wrote:
> If I have a list that looks like:
>
> [None, None, None, None, None, None, None, None, None, None,
> ['/atl/horseradishgrill_1'], None, None, None, None, None, None, None, None,
> None, None, None, None, None, None, None, None, None, None,
> ['/boston/archive'], None, None, None, ['/boston/cafe_fleuri'], None, None,
> None, None, None, None, None, None, None, None, ['/boston/rplace'],
> ['/boston/salamander'], None, ['/boston/test'], ['/boston/the_federalist'],
> None, ['/boston/yanks']]
>
> How can I remove those None elements in it? The code that I'm getting that
> from is, in part, this:
One way to do this is to use the functional tool filter():
###
def isTrue(x):
if x: return 1
else: return 0
cleanFiles = filter(isTrue, files)
###
That's one way of removing all the None's out of there: isTrue() is a
function that says 1 only when the filename is either nonempty or not
None.
Hmmm... In more Python 2.0 terms, it's doing something like this:
cleanfiles = [f for f in files if f != None]
Sorry, I'm a stickler for functional stuff sometimes... The list
comprehension way is probably a lot easier to read: it creates for us a
list of all files that aren't None.
We can extend this method to take care of both the None's and the badfiles
in one swoop:
chosen = [f for f in files if pick.search(f) and f != None]
should do it. (I renamed 'elements' to 'f' to save some space.)
Hope this helps!