This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: Lambda functions in list comprehensions
Type: Stage:
Components: Interpreter Core Versions: Python 2.3
process
Status: closed Resolution: fixed
Dependencies: Superseder:
Assigned To: jhylton Nosy List: jhylton, mwh, rhettinger, tomfinley
Priority: high Keywords:

Created on 2003-05-08 21:20 by tomfinley, last changed 2022-04-10 16:08 by admin. This issue is now closed.

Messages (4)
msg15928 - (view) Author: Thomas Finley (tomfinley) Date: 2003-05-08 21:20
Lambda functions that return a list built through a list comprehension 
used in a list comprehension cause Python to die.

Example:
[ (lambda a:[a**i for i in range(a+1)])(j) for j in range(5) ]

You can use "map" instead of list comprehension of course (as I 
illustrate in my example output), so this isn't a big deal, but I think it 
ought to work.

What follows this paragraph is an interactive session in Python, where 
I illustrate the workings of my lambda function to illustrate that it 
does work correctly in several circumstances, but not in a list 
comprehension.  I've done this with OS X Python 2.3b1, 2.2.2, 2.2, 
and Solaris Python 2.2a2 with the same results.
=========
Python 2.3b1 (#1, May  6 2003, 01:40:43) 
[GCC 3.1 20020420 (prerelease)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> (lambda a:[a**i for i in range(a+1)])(5)
[1, 5, 25, 125, 625, 3125]
>>> f = lambda a:[a**i for i in range(a+1)]
>>> [ f(i) for i in range(5) ]
[[1], [1, 1], [1, 2, 4], [1, 3, 9, 27], [1, 4, 16, 64, 256]]
>>> map(lambda a:[a**i for i in range(a+1)], range(5))
[[1], [1, 1], [1, 2, 4], [1, 3, 9, 27], [1, 4, 16, 64, 256]]
>>> [ (lambda a:[a**i for i in range(a+1)])(j) for j in range(5) ]
Fatal Python error: unknown scope for _[1] in <lambda>(1) in <stdin>
symbols: {'a': 12, '_[2]': 2, 'range': 8, 'i': 10}
locals: {'a': 0, '_[2]': 1, 'i': 2}
globals: {'range': True}

Abort
msg15929 - (view) Author: Michael Hudson (mwh) (Python committer) Date: 2003-05-09 11:19
Logged In: YES 
user_id=6656

Argh.
msg15930 - (view) Author: Raymond Hettinger (rhettinger) * (Python committer) Date: 2003-05-17 23:43
Logged In: YES 
user_id=80475

I can reproduce the error on Py2.1.3, Py2.2.2, and 
Py2.3b1.  

It should probably be fixed before Py2.2.3 goes out the 
door next week.
msg15931 - (view) Author: Jeremy Hylton (jhylton) (Python triager) Date: 2003-05-21 17:35
Logged In: YES 
user_id=31392

Fixed in rev. 2.285 of compile.c.
History
Date User Action Args
2022-04-10 16:08:39adminsetgithub: 38469
2003-05-08 21:20:13tomfinleycreate