unintuitive for-loop behavior

Rustom Mody rustompmody at gmail.com
Sat Oct 1 08:24:38 EDT 2016


On Saturday, October 1, 2016 at 5:02:30 PM UTC+5:30, Steve D'Aprano wrote:
> On Sat, 1 Oct 2016 01:44 pm, Rustom Mody wrote:
> 
> > Yes one basic problem with comprehensions in python is that they are
> > defined by assignment not binding to the comprehension variable
> 
> ¿Que Mr Fawlty?
> 
> I'm sorry, I don't understand you.
> 
> In Python, all assignments are name bindings. So you seem to be saying:
> 
>     one basic problem with comprehensions in python is that they 
>     are defined by binding (to the comprehension variable) not 
>     binding to the comprehension variable
> 
> which confuses me. How do you think that comprehension variables are
> different from all other variables?

Sorry... I guess you are right [for once ;-) ]
I was making a *generic* distinction between binding-constructs that *create*
variables, eg function-defs, lambdas, excepts, withs etc and assignment
that *changes* a binding.
This distinction is standard in compiled languages like C where a 
int x;
creates the x and 
x=rhs;
modifies it

C++ preserves this distinction in user defined types making sure that
the constructor called for an assignment and for an initialization are distinct
even though they look very similar:
x = rhs;
vs
T x = rhs;

In functional languages, both the dynamic ones like lisp as well as the static
ones like Haskell are very strict and sacrosanct about this distinction.

However in python this does not work because assignment both assigns and 
creates  the variable.

Interestingly there is this thread running right now on haskell-cafe:
https://groups.google.com/forum/#!topic/haskell-cafe/6tqMdy9nGdc
which is inspired by python's “batteries included” 
And there there is this comment:
«Python is even more imperative than C++ or Java, it's dynamically typed…» 
which (I guess) is because of exactly such features

Long story short: My saying “binding” is meaningless in python.
I should have said function-binding; ie the mechanism by which functions bind
their arguments *anew*
And then define comprehensions not as now done in terms of for loops that
mutatingly extend the list being built up but as recursive functions that get (re)called for every new value of the comprehension variable passed and therefore
fresh-bound as parameter


> 
> And while we're at it, what do you mean by "comprehension variable"? Are you
> talking about the variable that the comprehension is bound to:

> 
> comprehension_variable = [x+1 for x in sequence]
> 
> or are you talking about the loop variable inside the comprehension?
> 
> foo = [comprehension_variable+1 for comprehension_variable in sequence]
> 

Yeah by comprehension-variable I mean the one that sits left of the ‘in’ inside
The other obviously needn't exist



More information about the Python-list mailing list