Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #105844
| From | Jussi Piitulainen <jussi.piitulainen@helsinki.fi> |
|---|---|
| Newsgroups | comp.lang.python |
| Subject | Re: Why lambda in loop requires default? |
| Date | 2016-03-27 17:16 +0300 |
| Organization | A noiseless patient Spider |
| Message-ID | <lf5k2kouhu0.fsf@ling.helsinki.fi> (permalink) |
| References | <mailman.80.1459086902.28225.python-list@python.org> |
gvim writes: > Given that Python, like Ruby, is an object-oriented language why > doesn't this: > > def m(): > a = [] > for i in range(3): a.append(lambda: i) > return a > > b = m() > for n in range(3): print(b[n]()) # => 2 2 2 I'm going to suggest two variations that may or may not work for you, with very brief glosses. Just ignore them if you don't see their relevance. First, consider: def w(): a = [] for i in range(3): a.append(lambda: i) i = "!" return a b = w() for f in b: print(f()) # => ! ! ! (Those functions depend on the i in the loop.) > lambda i=i: i > > ... is needed to make it work in Python. Just wondered why? And second, consider: lambda x=i: x (Those functions are independent of the i in the loop.)
Back to comp.lang.python | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread
Why lambda in loop requires default? gvim <gvimrc@gmail.com> - 2016-03-27 02:46 +0100 Re: Why lambda in loop requires default? Jussi Piitulainen <jussi.piitulainen@helsinki.fi> - 2016-03-27 17:16 +0300 Re: Why lambda in loop requires default? Jussi Piitulainen <jussi.piitulainen@helsinki.fi> - 2016-03-27 18:15 +0300 Re: Why lambda in loop requires default? Ned Batchelder <ned@nedbatchelder.com> - 2016-03-27 08:29 -0700
csiph-web