Removing None objects from a sequence

alex23 wuwei23 at gmail.com
Fri Dec 12 10:45:55 CET 2008


On Dec 12, 7:18 pm, "Filip Gruszczyński" <grusz... at gmail.com> 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?

Rather than a list comprehension, use a generator expression:

for item in (x for x in sequence if x is not None):
   do_something(x)

This doesn't generate the intermediate list with None elements
removed, rather it steps one at a time through the original sequence
and only returns the non-None elements.



More information about the Python-list mailing list