, , ,

Recently I came across the following comp.lang.python usenet thread. urikaluzhny posted the following question:-

It seems that I rather frequently need a list or iterator of the form [x for x in <list> while <condition>]
And there is no one like this.
May be there is another short way to write it (not as a loop).

I think Paul Rubin gave a reasonable answer in which he said to use itertools.takewhile(condition, seq)

Other solutions were bigger ones i.e. the long way to write it.

I was thinking of the shortest way to do this, using pure python constructs. i.e without importing anything addional and I came up with the following:-

l = range(6)
1 if b!=4 else l.__delslice__(0,len(l)) for b in l][:-1]

I was wondering if anyone could come up with something more concise no matter how complex. Feel free to respond on the original thread or here[In which case I’ll shift the answers I consider reasonable onto the original thread using your name of course]. Or you could feel free to post at both places.


  1. The following proposed solution is not intended to be a solution, it goes completely against the zen of python. [Type import this into the python command interpreter]
  2. It is strongly undesireable for us humans to use anything that starts with __