473,769 Members | 5,518 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

List Comprehension Syntax

Does anyone here find the list comprehension syntax awkward?

I like it because it is an expression rather than a series of statements,
but it is a little harder to maintain it seems.

e.g. you could do:

result = []
for element in list:
if element[0:4] == 'blah':
result.append( element.replace ( 'blah', 'moof' ) )

or just:

result = [ element.replace ( 'blah', 'moof' ) for element in list if
element[0:4] == 'blah' ]

The second looks cleaner in some cases, but it is less maintainable. It
tends to promote long lines. It all seems to run together and such. And
often you would need to add another condition or modify it, it seems better
to use the first way even though it has the ugly extra init (and which would
cause more allocs than the list comprehension? because it wouldn't know the
size off the bat?)

I am in favor of short lines like I think Guido said in the style guide. I
like each line to be so simple as to not require any thinking reading it,
e.g.

I prefer:

x = c( d, e )
y = f( g, h )
z = b( x, y )
w = a( z )

to stuff like this:

w = a( b( c( d, e ), f( g, h ) ) )

It is more maintainable, when you need to make a change, just insert a line,
rather than having to decode an expression.

Along the same lines, it seems more maintainable to split things up.

You could do:

result = [
element.replace ( 'blah', 'moof' )
for element in list
if element[0:4] == 'blah' ]

I guess, but that seems awkward to me. Looks too much like a for loop and
an if, and then the value is at the top, which reads funny to me.
(Strangely putting it on one line doesn't read as funny, but it is less
readable.) Maybe I just have to get used to it. Which do you prefer?
Comments?

MB
Jul 18 '05
35 2981
Moosebumps wrote:
Just curious -- anyone care to tell me how they would format the above? (or
maybe you wouldn't write it all)


result = [x for x in range(10)
if x % 2 == 0
if x % 3 == 0
]

result = [x * y
for x in range(10) if x % 2 == 0
for y in range(10) if y % 3 == 0
]

Probably something like that?

-Peter
Jul 18 '05 #21

Moosebumps wrote:
Just curious -- anyone care to tell me how they would format the above? (or
maybe you wouldn't write it all)


Peter indents:
---------------
result = [x for x in range(10)
if x % 2 == 0
if x % 3 == 0
]

result = [x * y
for x in range(10) if x % 2 == 0
for y in range(10) if y % 3 == 0
]

-----------------

Nope, the only correct way is
result = [x for x in range(10)
if x % 2 == 0
if x % 3 == 0
]

result = [x * y
for x in range(10) if x % 2 == 0
for y in range(10) if y % 3 == 0
]

Because that's the way python-mode.el does it in emacs :-).

--
Ville Vainio http://tinyurl.com/2prnb
Jul 18 '05 #22
Andrea Griffini <ag****@tin.i t> wrote in message news:<f5******* *************** **********@4ax. com>...
On 10 Jul 2004 16:41:16 +0300, Ville Vainio <vi***@spammers .com>
wrote:
I think you'll find that you don't need to sacrifice any of your old
models or even aesthetic preferences to appreciate LCs.


I'm quite new to python, and I found LC quite simple to understand
and powerful. The only "suprising" part for me was that the looping
variable is not local... I slipped on that a couple of times.
A list comphrension is very "local" in my mind ... I would say that
[x*x for x in xrange(10)] is just a list of perfect squares, but
instead it's not... it's that AND the assignment to x of the value 9.

Andrea


Yup, scoping rules are usually the one confusing part of Python. I was
especially surprised by the result of:

l = [lambda y: x*y for x in range(10)]

which doesn't do remotely what you'd expect. Especially if you
learned about list comprehensions in Haskell, with no variable
assignments... :-)
Jul 18 '05 #23
Ville Vainio wrote:
Nope, the only correct way is
result = [x for x in range(10)
if x % 2 == 0
if x % 3 == 0
]

result = [x * y
for x in range(10) if x % 2 == 0
for y in range(10) if y % 3 == 0
]

Because that's the way python-mode.el does it in emacs :-).


Unless, of course, you leave the opening bracket as the last character
on the line, in which case python-mode will prefer you to do this:

result = [
x for x in range(10)
if x % 2 == 0
if x % 3 == 0
]

result = [
x * y
for x in range(10) if x % 2 == 0
for y in range(10) if y % 3 == 0
]

:)
Jul 18 '05 #24
Ville Vainio wrote:
Nope, the only correct way is

result = [x for x in range(10)
if x % 2 == 0
if x % 3 == 0
]

result = [x * y
for x in range(10) if x % 2 == 0
for y in range(10) if y % 3 == 0
]

Because that's the way python-mode.el does it in emacs :-).


Unfortunately, python-mode.el is wrong, since it results
in code that is harder to maintain (at least with another
editor).

Indentation that has to line up with random items on
the previous line, as opposed to the standard four spaces,
is clearly wrong.

But if you let emacs define the limits of your world, then
it's probably okay to do it that way. ;-)
Jul 18 '05 #25
[Peter Hansen]
Unfortunately, python-mode.el is wrong, since it results in code that
is harder to maintain (at least with another editor).
I'm not arguing here if `python-mode.el' is right or wrong.

However, for me at least, the greatest virtue of Python is that one can
write it legibly, and maintainability mainly results from legibility.

Being easier or harder to maintain with this or that editor is rather
irrelevant, if legibility is at stake. A lot of people are using lesser
editors anyway, and do all their alignment "by hand".
But if you let emacs define the limits of your world, then it's
probably okay to do it that way. ;-)


I do see the smiley. Yet, if people use an editor which is more helpful
on the side of legibility, it's not limitative, but plain good for them!

--
François Pinard http://www.iro.umontreal.ca/~pinard
Jul 18 '05 #26
François Pinard wrote:
... for me at least, the greatest virtue of Python is that one can
write it legibly, and maintainability mainly results from legibility.
I don't find the legibility of the carefully aligned version of
that code to be higher than the simpler "indent the standard amount"
version of the code. Sometimes consistency is not foolish.

As for maintainability , the problem is not that other people
use an editor which makes it harder to produce the same level
of legibility (since I find the legibility the same or worse
with the "artistic" alignment). The problem is that other people
who use another editor (and it should be very clear that there
are such people and will always be) will find it much harder to
maintain alignment which, without editor support, requires
careful manual alignment.
Being easier or harder to maintain with this or that editor is rather
irrelevant, if legibility is at stake. A lot of people are using lesser
editors anyway, and do all their alignment "by hand".


If they do the alignment that way, making things carefully line
up with the parentheses, and manually, they are definitely wasting
their time, IMHO, because there is NO increase in legibility. I
used to do that... same as how I used to waste time lining up the
equals signs in initialization sections of my code. (Now the
only place I do such things is in sections where series of related
constants are assigned, since only there does it really produce
increased readability).

In a lot of ways, this is probably the same argument as that against
using TABs. People who like TABs most often seem to like them
because they feel TABs make it easier to tune things to their own
particular (more aesthetically pleasing) indentation standards.

In fact, since they are gaining arguably nothing (for example,
there are arguments that could be made about four spaces being
the optimal size, if we wanted to go there), but are making
maintenance harder for others, it's a net negative in the greater
scheme of things, though perhaps easier on themselves at
least in the short term.

(Wow... a simultaneous segue into both the tab war and the editor
wars! I think I'd better leave now...)

-Peter
Jul 18 '05 #27
>>>>> "Peter" == Peter Hansen <pe***@engcorp. com> writes:

Peter> But if you let emacs define the limits of your world, then
Peter> it's probably okay to do it that way. ;-)

It's just the path of least resistance - any other indentation
requires manual work, and won't reindent properly when pressing <tab>
on the line.

Anyway, the point is mostly moot because

blah = [
i + 1
for i in range(10)
if i != 3
]

indents the way you want it to, and that's the way I usually do it
anyway. I just M-x indent-region'ed your code snippet :).

Perhaps this is something that could be fixed in python-mode.el? I
mean making the indentation on the next line be previous_line + 4 in
bracket-opening situations... Or is the current behaviour better in
some generally agreed way?

--
Ville Vainio http://tinyurl.com/2prnb
Jul 18 '05 #28
[Peter Hansen]
François Pinard wrote:
... for me at least, the greatest virtue of Python is that one can
write it legibly, and maintainability mainly results from legibility.

I don't find the legibility of the carefully aligned version of
that code to be higher than the simpler "indent the standard amount"
version of the code.
That's the important point. Write for legibility! :-)
[...] same as how I used to waste time lining up the equals signs in
initialization sections of my code.
Yes, this is often abused, with not much gain. Agreed!
(Wow... a simultaneous segue into both the tab war and the editor
wars! I think I'd better leave now...)


We'll surely meet somewhere else, anyway! :-)

--
François Pinard http://www.iro.umontreal.ca/~pinard
Jul 18 '05 #29
>>>>> "Peter" == Peter Hansen <pe***@engcorp. com> writes:

Peter> If they do the alignment that way, making things carefully
Peter> line up with the parentheses, and manually, they are
Peter> definitely wasting their time, IMHO, because there is NO
Peter> increase in legibility.

Except that if you write things like

a=[[[1, 2],
[3, 4],
[5, 6]],
[[7, 8],
[5, 6]],
[9]]

as

a=[[[1, 2],
[3, 4],
[5, 6]],
[[7, 8],
[5, 6]],
[9]]

and say there is no lose of legibility, then I'll seriously question
your taste.

BTW, for somebody with python-mode installed and is using Emacs, it is
actually *harder* and a *bigger* waste of time to write the code as
you proposed, because by default whenever you press enter the cursor
is already at exactly the location in the former style, and you got to
count spaces in order to go to the place you proposed.

Regards,
Isaac.
Jul 18 '05 #30

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

Similar topics

14
15250
by: jsaul | last post by:
Hi there, wouldn't it be useful to have a 'while' conditional in addition to 'if' in list comprehensions? foo = for i in bar: if len(i) == 0: break foo.append(i)
6
1495
by: Eric | last post by:
Pythonistas, I seem at a loss for a List Comprehension syntax that will do what I want. I have a list of string position spans: >>> breaks the first pair representing: someString
24
3356
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 which speeds things up for larger lists but why was it necessary to add it instead of improving list...
15
1624
by: Darren Dale | last post by:
Hi, I need to replace the following loop with a list comprehension: res= for i in arange(10000): res=res+i In practice, res is a complex 2D numarray. For this reason, the regular output of a list comprehension will not work: constructing a list of every
6
2172
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
4
1813
by: Gregory Guthrie | last post by:
Sorry for a simple question- but I don't understand how to parse this use of a list comprehension. The "or" clauses are odd to me. It also seems like it is being overly clever (?) in using a lc expression as a for loop to drive the recursion. Thanks for any insight! Gregory
6
2006
by: fdu.xiaojf | last post by:
Hi all, I can use list comprehension to create list quickly. So I expected that I can created tuple quickly with the same syntax. But I found that the same syntax will get a generator, not a tuple. Here is my example: In : a = (i for i in range(10)) In : b =
4
3057
by: beginner | last post by:
Hi All, If I have a list comprehension: ab= c = "ABC" print c
0
1792
by: Hatem Nassrat | last post by:
on Wed Jun 13 10:17:24 CEST 2007, Diez B. Roggisch deets at nospam.web.de wrote: Well I have looked into this and it seems that using the list comprehension is faster, which is reasonable since generators require iteration and stop iteration and what not.
0
9589
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 usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9423
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 synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
9994
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 most users, this new feature is actually very convenient. If you want to control the update process,...
0
9863
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8872
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7409
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 instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6673
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 into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
3959
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
3
2815
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 effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.