473,769 Members | 5,871 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
Ville Vainio wrote:
>>"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.


Not sure what you mean here. The indentation approach I'm
referring to (i.e. the "standard" way, as opposed to what I
was calling the "artistic" way) is just to hit tab in precisely
the same way you would if you were indenting an "if" block.
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 :).
Not sure which code-snippet you refer to, but the ones that I
typed were indented the same way, except perhaps that I put
the first expression the same line as the opening bracket.
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?


Nope, definitely not in a generally agreed way. I don't think anyone
thinks this issue is on par with the tab war though, so until that
particular war is won, we're best off leaving this issue to personal
preference. (That is to say, "forever". :-)

-Peter
Jul 18 '05 #31
Isaac To wrote:
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.
Ugh. But nobody should write something like the first one, either.
(And I won't say how it should be written without a real example,
since otherwise we can each contrive all kinds of interesting and
meaningless ways to format something that nobody would actually
write.)
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.


Not sure which one you think I proposed, but you definitely don't
have to count any spaces in order to do what I suggested. You
hit ENTER and TAB (once), exactly as you would with any other
block. Note that this (hitting TAB once) of course relies on
an editor which auto-indents to the same level as the preceding
line of code by default. Any editor which does not do at least
this, these days, is broken. But counting spaces would be silly.
What editor are you using that would force you to do that? vi
without a Python configuration?

-Peter
Jul 18 '05 #32
I don't agree that the second is "less maintainable",
but do find it "wordy" for little reason. Try:

result=[x.replace('blah ','moof') for x in L if x.startswith('b lah')]

or if you prefer short lines:

result=[x.replace('blah ','moof') \
for x in L \
if x.startswith('b lah')]

Note: BAD idea to call variable 'list' as it kills the
list function for remainder of Python session (I changed
to L). For same reason never call variable 'dict', 'str',
etc. Using startswith also takes care of not having to
get the slice correct (which is easier to maintain should
you change 'blah' to something else, you don't have to
mess with the slice).

Larry Bates
Syscon, Inc.

"Moosebumps " <cr**@crap.crap > wrote in message
news:j9******** *********@newss vr25.news.prodi gy.com...
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 #33
>>>>> "Peter" == Peter Hansen <pe***@engcorp. com> writes:

Peter> Not sure what you mean here. The indentation approach I'm
Peter> referring to (i.e. the "standard" way, as opposed to what I
Peter> was calling the "artistic" way) is just to hit tab in
Peter> precisely the same way you would if you were indenting an
Peter> "if" block.

In emacs, tab is 'indent-line', which gives the line "correct"
indentation. Occasionally one needs to dedent a line manually to close
a block. Pressing <enter> puts the cursor in the right place
immediately (indenting on ':', dedenting on 'return').

if 1:
hui();

If I press tab on line with hui(), the result is

if 1:
hui();

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 :).


Peter> Not sure which code-snippet you refer to, but the ones that
Peter> I typed were indented the same way, except perhaps that I
Peter> put the first expression the same line as the opening
Peter> bracket.

Yes, and that made the difference.
--
Ville Vainio http://tinyurl.com/2prnb
Jul 18 '05 #34
In article <HI************ *******@newssvr 27.news.prodigy .com>,
Moosebumps <cr**@crap.crap > wrote:
result = [x for x in range(10) if x % 2 == 0 if x % 3 == 0]
result[0, 6] result = [ x*y for x in range(10) if x%2 == 0 for y in range(10) if y %3 == 0] result

[0, 0, 0, 0, 0, 6, 12, 18, 0, 12, 24, 36, 0, 18, 36, 54, 0, 24, 48, 72]

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


Wouldn't use either.
--
Aahz (aa**@pythoncra ft.com) <*> http://www.pythoncraft.com/

Barbara Boxer speaks for me:
http://buffaloreport.com/2004/040713....marriage.html
Jul 18 '05 #35
In article <cd**********@p anix2.panix.com >, aa**@pythoncraf t.com (Aahz)
wrote:
In article <HI************ *******@newssvr 27.news.prodigy .com>,
Moosebumps <cr**@crap.crap > wrote:
> result = [x for x in range(10) if x % 2 == 0 if x % 3 == 0]
> result

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

3 == 0]
> result

[0, 0, 0, 0, 0, 6, 12, 18, 0, 12, 24, 36, 0, 18, 36, 54, 0, 24, 48, 72]

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


Wouldn't use either.


I would probably use instead something like
[x for x in range(0,10,6)] [0, 6] [x*y for x in range(0,10,2) for y in range(0,10,3)]

[0, 0, 0, 0, 0, 6, 12, 18, 0, 12, 24, 36, 0, 18, 36, 54, 0, 24, 48, 72]

I think two for or if clauses in a comprehension is the most I'd want to
use on a regular basis. I certainly wouldn't use two ifs in a row as in
your first example, I'd use and instead.

--
David Eppstein
Computer Science Dept., Univ. of California, Irvine
http://www.ics.uci.edu/~eppstein/
Jul 18 '05 #36

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,...
0
10045
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
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();...
0
5447
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
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
2
3562
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
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.