473,569 Members | 2,880 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

list comprehensions


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 this description, feel free to go back to
whatever you were doing before. If you're still here, though, I invite you to
consider the following definition:

partitions = lambda n: [[n]]+[[k]+x for x in partitions(n-k) for k in
range(1,n)]

As defined above, the function raises an exception when you call it ('k'
referenced before assignment). For the sake of clarity, here is workable code
expressing the same intention:

def partitions(n):
reVal=[[n]]
for k in range(1,n):
for x in partitions(n-k):
reVal.append([k]+x)
return reVal

So I guess what I want to ask is: Can somebody explain the semantics of list
comprehensions to me? Or even better: Can somebody tell me where to look in the
documentation to find out about list comprehensions? All donations gratefully
received.

Peace
Jul 18 '05 #1
2 1626
Elaine Jackson wrote:
List comprehensions don't work the way you intuitively expect them to work. I
How can you say such a thing. 100 Haskell programmers have been asked
about Python list comprehension and all found it intuitive.
partitions = lambda n: [[n]]+[[k]+x for x in partitions(n-k) for k in
range(1,n)]

As defined above, the function raises an exception when you call it ('k'
referenced before assignment).
Try a simpler example and you'll see the order of execution with nested
loops:
[(a, x) for a in "ab" for x in "xy"] [('a', 'x'), ('a', 'y'), ('b', 'x'), ('b', 'y')]
So I guess what I want to ask is: Can somebody explain the semantics of list
comprehensions to me? Or even better: Can somebody tell me where to look in the
documentation to find out about list comprehensions? All donations gratefully
received.


http://www.python.org/doc/2.3.3/ref/lists.html, especially "each of the
for or if clauses a block, nesting from left to right".
partitions = lambda n: [[n]]+[[k]+x for k in range(1,n) for x in partitions(n-k)] partitions (3)

[[3], [1, 2], [1, 1, 1], [2, 1]]

Daniel
Jul 18 '05 #2

"Elaine Jackson" <el************ ***@home.com> wrote in message
news:yjZcc.4282 3$Pk3.9547@pd7t w1no...

List comprehensions don't work the way you intuitively expect them to work.

One of my pet posting peeves is when people ascribe their own
characteristics to others, as when they write 'you' when they really mean,
or should have meant, 'I'. But nevermind.
I realize many people have no intuitions about how list comprehensions 'should' work,
List comprehensions are sufficiently 'artificial' that I would advise
anyone to avoid the temptation to intuit how they work without consulting
the manual, tutorials, or other written explanations.

The Python Reference Manual Index, section L, entry List..comprehen sions
takes one to subsection 5.2.4 List displays. The last two sentences
therein read

"When a list comprehension is supplied, it consists of a single expression
followed by at least one for clause and zero or more for or if clauses. In
this case, 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."

OK, takes a couple of readings and maybe some working examples.
partitions = lambda n: [[n]]+[[k]+x for x in partitions(n-k) for k in
range(1,n)]

As defined above, the function raises an exception when you call it ('k'
referenced before assignment).
Of course, you have the two for clauses reversed, as the error message
might suggest to an experienced Pythoneer. As the manual specifies, for/if
clauses nest *left to right*. To match the double loop below, you want
instead

[[k]+x for k in range(1,n) for x in partitions(n-k)]
def partitions(n):
reVal=[[n]]
for k in range(1,n):
for x in partitions(n-k):
reVal.append([k]+x)
return reVal


Terry J. Reedy


Jul 18 '05 #3

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

Similar topics

24
3332
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 see that generator expressions have been added to the language with 2.4 and I question the need for it. I know that it allows for lazy evaluation...
9
2346
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: based on tests run under Python 2.2, map calls are roughly twice as fast as equivalent for loops, and list comprehensions are usually very slightly...
42
2586
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 original list is , I want to end up with . Here is the way I'm doing this now: def straightforward_collapse(myList):
23
2233
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 confused, though - when would I use a list comp instead of a generator expression if I'm going to require 2.4 anyway? Thanks, <mike --
24
3914
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 am not sure how to conver: Given three tuples of length n, b,i and d, I now do:
30
3447
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, is that dict comprehensions don't gain you >> much at all over the dict() constructor plus a generator expression, >> e.g.: >> dict((i,...
7
1606
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 > obviously be a Py3k thing, though. Alex Martelli wrote: > I fully agree, but the BDFL has already (tentatively, I hope) > Pronounced that the form will...
6
2155
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. === PEP: xxx Title: Unification of for-statement and list-comprehension syntax
6
1386
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 namespace with illegal names (names can't contain brackets). Can't someone come up with a better hack than this? How about using "_1", "_2", etc,...
0
7703
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7619
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
1
7681
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
1
5514
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
5228
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3662
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3651
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2118
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
0
950
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

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.