Having both if() and for() statements in one liner

Tim Chase python.list at tim.thechases.com
Tue Sep 17 10:17:44 EDT 2013


On 2013-09-17 16:21, Ferrous Cranus wrote:
> I just want to say tot he program that
> 
> that only run the for statement if and only if person=='George'
> 
> I dont see nay reason as to why this fails
> 
> perhaps like:
> 
> for times in range(0, 5) if person=='George':
> 
> but that fails too...
> there must be written on soem way.

The canonical way to do this is the obvious:

  if person == "George":
    for times in range(0, 5):
      ...

That said, you can do stupid things to abstract the logic like

  def iterate_if(condition, iterable):
    if condition:
      for item in iterable:
        yield item

which you can use something like

  for times in iterate_if(person == "George", range(0,5)):
    ...

but I don't advise it.  Mainly, because the iterable will be
evaluated when passed as an argument, which incurs the runtime cost.
In the canonical form, if the test isn't passed, the range(n,m) is
never even evaluated.

-tkc







More information about the Python-list mailing list