[Tutor] Fw: Misc question about scoping
Steven D'Aprano
steve at pearwood.info
Fri Jun 4 01:56:42 CEST 2010
On Fri, 4 Jun 2010 09:00:13 am ALAN GAULD quoted Tino Dai who wrote:
> "Tino Dai" <oberoc at gmail.com> wrote
[...]
> >> I have code that is unpythonic in many places. It works, but
> >> it's ugly. One of those unpythonic places is I'm initializing some
> >> variable such as a list,dict, or whatever outside of if/while/for
> >> in block to use later. So, I'm cleaning those places up.
> >>
> >> For example, my present code looks like:
> >> L = [] # Needed or L doesn't exist outside of for loop
> >> below for o in a:
> >> if o.someAttribute > someConstant:
> >> L.append(o.someOtherAttribute)
> >>
> >> .... later in code ....
> >> <some use of L>
There's nothing unpythonic about that code. For loops existed in Python
since the very earliest days, which is *at least* 1991, while list
comprehensions are a newcomer.
But if you insist on a list comprehension, you can re-write the above
for-loop as:
L = [o.someOtherAttribute for o in a if o.someAttribute > someConstant]
--
Steven D'Aprano
More information about the Tutor
mailing list