Removing None objects from a sequence

Stephen Thorne stephen.thorne at gmail.com
Fri Dec 12 05:49:48 EST 2008


On 2008-12-12, 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. And I would like to get something faster.
> 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. 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?

There's a little hack that will remove all elements from a list that
are 'False' when considered as a boolean. So None, [], '', False,
etc.

filter(None, myseq)

an example:

>>> l = ['1', 2, 0, None, '5']
>>> filter(None, l)
['1', 2, '5']

-- 
Regards,
Stephen Thorne
Development Engineer
NetBox Blue - 1300 737 060

Scanned by the NetBox from NetBox Blue
(http://netboxblue.com/)


Can you afford to be without a NetBox? 
Find out the real cost of internet abuse with our ROI calculator.
http://netboxblue.com/roi



Scanned by the NetBox from NetBox Blue
(http://netboxblue.com/)




More information about the Python-list mailing list