Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #99571
| From | Marko Rauhamaa <marko@pacujo.net> |
|---|---|
| Newsgroups | comp.lang.python |
| Subject | Re: What does a list comprehension do |
| Date | 2015-11-26 14:56 +0200 |
| Organization | A noiseless patient Spider |
| Message-ID | <87k2p4ex5x.fsf@elektro.pacujo.net> (permalink) |
| References | <CAPTjJmpwjWnF=d6mpgbKS1biVLoR4APutgyH0n9t6CJ=Kh4dCg@mail.gmail.com> <877fldnm9z.fsf@handshake.de> <mailman.73.1448459485.20593.python-list@python.org> <pan.2015.11.26.11.13.43.440000@nowhere.invalid> <mailman.132.1448538769.20593.python-list@python.org> |
Antoon Pardon <antoon.pardon@rece.vub.ac.be>:
> Personnaly I would prefer:
>
>>>> q = [(lambda i: lambda x: i * x)(i) for i in range(4)]
>>>> q[0](1), q[3](1)
> (0, 3)
>
> And this is where I ask whether it would be worth the effort to change
> the behaviour of python.
Don't go there.
Consider:
q = []
n = 0
x = "hello"
for i in range(4):
def stepper():
global n
n += 1
return i * x
q.append(stepper)
print(n)
print(q[1]())
print(n)
x = "there"
print(q[3]())
print(n)
which prints:
0
hellohellohello
1
theretherethere
2
after your change, you'd get:
0
hello
0
hellohellohello
0
> It also seems that people who try this for the first time are
> surprised with what they get and seem to expect there list
> comprehension to act as if they had written the second version.
I might trip over that one, too. Still, nothing should be changed.
Marko
Back to comp.lang.python | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread
What does a list comprehension do (was: Late-binding of function defaults (was Re: What is a function parameter =[] for?)) Antoon Pardon <antoon.pardon@rece.vub.ac.be> - 2015-11-25 14:51 +0100
Re: What does a list comprehension do (was: Late-binding of function defaults (was Re: What is a function parameter =[] for?)) Nobody <nobody@nowhere.invalid> - 2015-11-26 11:13 +0000
Re: What does a list comprehension do Antoon Pardon <antoon.pardon@rece.vub.ac.be> - 2015-11-26 12:52 +0100
Re: What does a list comprehension do Marko Rauhamaa <marko@pacujo.net> - 2015-11-26 14:56 +0200
Re: What does a list comprehension do Antoon Pardon <antoon.pardon@rece.vub.ac.be> - 2015-11-26 14:33 +0100
Re: What does a list comprehension do Marko Rauhamaa <marko@pacujo.net> - 2015-11-26 15:56 +0200
Re: What does a list comprehension do Antoon Pardon <antoon.pardon@rece.vub.ac.be> - 2015-11-26 15:26 +0100
Re: What does a list comprehension do Marko Rauhamaa <marko@pacujo.net> - 2015-11-26 17:36 +0200
Re: What does a list comprehension do Antoon Pardon <antoon.pardon@rece.vub.ac.be> - 2015-11-26 20:18 +0100
Re: What does a list comprehension do Jussi Piitulainen <harvest@is.invalid> - 2015-11-26 18:11 +0200
csiph-web