A C-like if statement

Kay Schluehr kay.schluehr at gmx.net
Fri Feb 24 22:49:27 EST 2006


Paul Rubin wrote:
> "Kay Schluehr" <kay.schluehr at gmx.net> writes:
> > Hmm. A statement has side-effects but it returns no value. And yes, you
> > can create a name within an expression producing a value in Python,
> > using a list/generator comprehension. The solution to Bob's problem
> > would look like this:
> >
> > if (I for I in (a.find("3"),) ) != -1:
> >      print "It's here: ", I
> > else:
> >      print "No 3's here"
>
> I think that works for list comprehensions but not generator
> comprehensions.  With generator comprehensions, the index variable's
> scope is limited to the comprehension.

Right. It becomes even more ugly yet:

if [I for I in ("1,2,3".find("3"),) ] != [-1]:
     print "It's here: ", I
else:
     print "No 3's here"

> With list comprehensions
> there's a wart in that the index variable is still around afterwards.

Definitely, but index variable survival is nothing that entered Python
with list-comps:

for k in range(2):
    print k

>>> k
1

Kay




More information about the Python-list mailing list