473,387 Members | 3,810 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

Bug in list comprehensions?

I was playing with list comprehensions, to try and work out how doubled
up versions work (like this one from another thread: [i for i in
range(9) for j in range(i)]). I think I've figured that out, but I
found something strange along the way:
alpha = ["one", "two", "three"]
beta = ["A", "B", "C"]
[x for x in alpha for y in beta] ['one', 'one', 'one', 'two', 'two', 'two', 'three', 'three', 'three'] [x for x in y for y in beta] ['C', 'C', 'C'] beta = [alpha, alpha, alpha]
beta [['one', 'two', 'three'], ['one', 'two', 'three'], ['one', 'two',
'three']] [x for x in y for y in beta] ['C', 'C', 'C'] [y for y in beta] [['one', 'two', 'three'], ['one', 'two', 'three'], ['one', 'two',
'three']] [x for x in y for y in beta]

['one', 'one', 'one', 'two', 'two', 'two', 'three', 'three', 'three']

Shoudn't both lines '[x for x in y for y in beta]' produce the same
list?
I'm guessing I'm the one confused here... but I'm confused! What's
going on?

Iain

Jun 7 '06 #1
3 1130
Iain King wrote:
[x for x in y for y in beta] ['C', 'C', 'C'] [y for y in beta] [['one', 'two', 'three'], ['one', 'two', 'three'], ['one', 'two',
'three']] [x for x in y for y in beta]

['one', 'one', 'one', 'two', 'two', 'two', 'three', 'three', 'three']

Shoudn't both lines '[x for x in y for y in beta]' produce the same
list?


[x for x in y for y in beta] is a shorthand for:

tmp = []
for x in y:
for y in beta:
tmp.append(x)

So x iterates over whatever y is before the loop starts, and y iterates
over beta (but that doesn't affect what x is iterating over).

The important thing is to remember that the order of 'for' and 'if'
statements is the same as though you had written the for loop out in full.
Jun 7 '06 #2
Iain King wrote:
I'm guessing I'm the one confused here... but I'm confused! What's
going on?


reading the documentation may help:

/.../ the elements of the new list are those that would be produced
by considering each of the for or if clauses a block, nesting from left
to right, and evaluating the expression to produce a list element each
time the innermost block is reached.

the clauses nest from left to right, not from right to left, so "[x for
x in y for y in beta]" is equivalent to

out = []
for x in y:
for y in beta:
out.append(x)

</F>

Jun 7 '06 #3
Fredrik Lundh <fr*****@pythonware.com> wrote:
Iain King wrote:
I'm guessing I'm the one confused here... but I'm confused! What's
going on?

the clauses nest from left to right, not from right to left, so "[x for
x in y for y in beta]" is equivalent to

out = []
for x in y:
for y in beta:
out.append(x)


And a list comprehension doesn't get a namespace to itself (cf.
generator comprehensions) so "leaks" its variables. Exactly as
above. So the y being iterated over in "for x in y" is the y
from the previous inner iteration ("for y in beta").

--
\S -- si***@chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/
___ | "Frankly I have no feelings towards penguins one way or the other"
\X/ | -- Arthur C. Clarke
her nu becomež se bera eadward ofdun hlęddre heafdes bęce bump bump bump
Jun 7 '06 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: Elaine Jackson | last post by:
List comprehensions don't work the way you intuitively expect them to work. I realize many people have no intuitions about how list comprehensions 'should' work, so if you recognize yourself in...
24
by: Mahesh Padmanabhan | last post by:
Hi, When list comprehension was added to the language, I had a lot of trouble understanding it but now that I am familiar with it, I am not sure how I programmed in Python without it. Now I...
9
by: Neuruss | last post by:
I have a doubt regarding list comprehensions: According to Mark Lutz in his book Learning Pyhon: "...there is currently a substantial performance advantage to the extra complexity in this case:...
42
by: Alan McIntyre | last post by:
Hi all, I have a list of items that has contiguous repetitions of values, but the number and location of the repetitions is not important, so I just need to strip them out. For example, if my...
23
by: Mike Meyer | last post by:
Ok, we've added list comprehensions to the language, and seen that they were good. We've added generator expressions to the language, and seen that they were good as well. I'm left a bit...
24
by: Mandus | last post by:
Hi there, inspired by a recent thread where the end of reduce/map/lambda in Python was discussed, I looked over some of my maps, and tried to convert them to list-comprehensions. This one I...
30
by: Steven Bethard | last post by:
George Sakkis wrote: > "Steven Bethard" <steven.bethard@gmail.com> wrote: >> Dict comprehensions were recently rejected: >> http://www.python.org/peps/pep-0274.html >> The reason, of course,...
7
by: Steven Bethard | last post by:
Tom Anderson <twic@urchin.earth.li> wrote: > Sounds good. More generally, i'd be more than happy to get rid of list > comprehensions, letting people use list(genexp) instead. That would >...
6
by: Heiko Wundram | last post by:
Hi all! The following PEP tries to make the case for a slight unification of for statement and list comprehension syntax. Comments appreciated, including on the sample implementation. ===...
6
by: Lonnie Princehouse | last post by:
List comprehensions appear to store their temporary result in a variable named "_" (or presumably "_", "_" etc for nested comprehensions) In other words, there are variables being put into the...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.