Removing None objects from a sequence

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Fri Dec 12 13:21:55 CET 2008


On Fri, 12 Dec 2008 10:18:35 +0100, Filip Gruszczyński
wrote:

> Hi!
> 
> I would like to iterate over a sequence nad ignore all None objects. The
> most obvious way is explicitly checking if element is not None, but it
> takes too much space.

Too much space???

seq = [x for x in seq if x is not None]

It's one line, less than 40 characters. If your hard disk is so full that 
you're worrying about 40 characters, I suggest you need a bigger disk.


> And I would like to get something faster.

Faster than what? What speed do we have to beat? 


> I can use
> [ sth for sth in self.__sth if not sth is None ], but I don't know if
> that's the best way. 

Who cares if it's the "best" way? What's important is, is it good enough?

It is easier to optimize correct code than to correct optimized code. Get 
your code working first, then worry about shaving microseconds off the 
runtime *if you need to*.


> I checked itertools, but the only thing that seemed
> ok, was ifilter - this requires seperate function though, so doesn't
> seem too short. How can I get it the shortest and fastest way?

You could do this:

seq = filter(None, seq)

but only if you know that seq doesn't contain any false objects other 
than None.


-- 
Steven



More information about the Python-list mailing list