473,769 Members | 4,831 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Proposal: [... for ... while cond(x)]

I suggest a new extension of the list comprehension syntax:

[x for x in xs while cond(x)]

which would be equivalent to

list(itertools. takewhile(cond, xs))

+ Since Python favors list comprehensions over map, filter, and reduce,
this would be the preferred way to do this
+ "Takewhile operations" occur often, at least for me
+ I don't think it would break any existing syntax

An analogous syntax for dropwhile would be nice, but I can't think of
one.

This is not a PEP because it's a very simple idea and probably not just
anyone (read: me) can write and submit one. If there has been a PEP for
this, I've missed it; if not, it would be nice if someone wrote one.

Discuss.

Aug 6 '06 #1
12 1730
Eighty wrote:
I suggest a new extension of the list comprehension syntax:

[x for x in xs while cond(x)]

which would be equivalent to

list(itertools. takewhile(cond, xs))
What would this syntax offer that:

[x for x in takewhile(cond, xs)]

doesn't currently offer? (Apart, that is, from saving you 3 characters of
typing)
Aug 6 '06 #2

Duncan Booth wrote:
Eighty wrote:
I suggest a new extension of the list comprehension syntax:

[x for x in xs while cond(x)]

which would be equivalent to

list(itertools. takewhile(cond, xs))

What would this syntax offer that:

[x for x in takewhile(cond, xs)]

doesn't currently offer? (Apart, that is, from saving you 3 characters of
typing)
The same thing that [f(x) for x in xs] offers that map(f, xs) doesn't,
and the same thing that [x for x in xs if f(x)] offers that filter(f,
xs) doesn't. It's more "pythonic". You can use an expression for cond
instead of a lambda.

Aug 6 '06 #3
Eighty wrote:
>
Duncan Booth wrote:
>Eighty wrote:
I suggest a new extension of the list comprehension syntax:

[x for x in xs while cond(x)]

which would be equivalent to

list(itertools. takewhile(cond, xs))

What would this syntax offer that:

[x for x in takewhile(cond, xs)]

doesn't currently offer? (Apart, that is, from saving you 3
characters of typing)

The same thing that [f(x) for x in xs] offers that map(f, xs) doesn't,
and the same thing that [x for x in xs if f(x)] offers that filter(f,
xs) doesn't. It's more "pythonic". You can use an expression for cond
instead of a lambda.

No, the list comprehension lets you write an expression directly avoiding a
function call, and it also allows you to add in a condition which can be
used to filer the sequence. Your proposal adds nothing.
Aug 6 '06 #4
On Sun, 06 Aug 2006 18:59:39 +0000 (GMT)
Duncan Booth <du**********@i nvalid.invalidw rote:

# I suggest a new extension of the list comprehension syntax:
#
# [x for x in xs while cond(x)]
#
# which would be equivalent to
#
# list(itertools. takewhile(cond, xs))
#>
#What would this syntax offer that:
#>
# [x for x in takewhile(cond, xs)]
#>
#doesn't currently offer?
#
# The same thing that [f(x) for x in xs] offers that map(f, xs) doesn't,
# and the same thing that [x for x in xs if f(x)] offers that filter(f,
# xs) doesn't. It's more "pythonic". You can use an expression for cond
# instead of a lambda.
#
#No, the list comprehension lets you write an expression directly
#avoiding a function call, and it also allows you to add in a
#condition which can be used to filer the sequence.

I am not sure if I understand you correctly, but... Does it?
>>a = [0,1,2,3,7,8,9]
[x for x in takewhile(lambd a x: x in a, range(10))]
[0, 1, 2, 3]
>>[x for x in takewhile(x in a, range(10))]
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: 'bool' object is not callable

Did I miss something? Notice that using "if" gives different result:
>>[x for x in range(10) if x in a]
[0, 1, 2, 3, 7, 8, 9]

#Your proposal adds nothing.

Well, I am not sure how useful the proposal really is, but it seems to
add *something* if it would allow for things like:
[x for x in range(10) while x in a]

--
Best wishes,
Slawomir Nowaczyk
( Sl************* **@cs.lth.se )

Women who seek to be equal to men lack ambition.

Aug 6 '06 #5
No, the list comprehension lets you write an expression directly avoiding a
function call, and it also allows you to add in a condition which can be
used to filer the sequence. Your proposal adds nothing.
It does. Consider this:

whatever = [x for x in xrange(10000000 00) while x < 10]
That would run only in a splitsecond of what the whole listcomp would.
Yet I still fail to see that this is a really useful use-case. takewhile
is easily abstracted away as map and reduce and filter are using lambda
- which I'm a modest supporter of.

But functions that are monotonic such that the takewhile really offers a
advantage over the much more general listcomp + if are IMHO way to
seldom to justify a new syntax.

The overall complexity is still O(n).

Regards,

Diez
Aug 7 '06 #6
Diez B. Roggisch wrote:
>No, the list comprehension lets you write an expression directly
avoiding a function call, and it also allows you to add in a
condition which can be used to filer the sequence. Your proposal adds
nothing.

It does. Consider this:

whatever = [x for x in xrange(10000000 00) while x < 10]
That would run only in a splitsecond of what the whole listcomp would.
Except that the comparable listcomp today is:

whatever = [x for x in takewhile(lambd a x: x < 10, xrange(10000000 00))]

which also runs in a split second.

Actually, the OP was correct, it does add something: it removes the need
for a function or lambda in the takewhile just as the original listcomp
removes a function or lambda compared with the map version.
Aug 7 '06 #7
Slawomir Nowaczyk wrote:
#No, the list comprehension lets you write an expression directly
#avoiding a function call, and it also allows you to add in a
#condition which can be used to filer the sequence.

I am not sure if I understand you correctly, but... Does it?
>>>a = [0,1,2,3,7,8,9]
[x for x in takewhile(lambd a x: x in a, range(10))]
[0, 1, 2, 3]
>>>[x for x in takewhile(x in a, range(10))]
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: 'bool' object is not callable

Did I miss something?
Yes, you missed out a lambda (so I was wrong, your suggestion would
actually gain you more than 3 characters of typing)

Try:
>>a = [0,1,2,3,7,8,9]
[x for x in takewhile(lambd a x:x in a, range(10))]
[0, 1, 2, 3]

For this particular expression you could also write:
>>[x for x in takewhile(a.__c ontains__, range(10))]
[0, 1, 2, 3]

or with Python 2.5 we can avoid referencing __contains__ with the following
variant:
>>from itertools import takewhile
from functools import partial
from operator import contains
a = [0,1,2,3,7,8,9]
[x for x in takewhile(parti al(contains,a), range(10))]
[0, 1, 2, 3]
>>>
Aug 7 '06 #8
Duncan Booth <du**********@i nvalid.invalidw rote in
news:Xn******** *************** **@127.0.0.1:
Diez B. Roggisch wrote:
>>No, the list comprehension lets you write an expression directly
avoiding a function call, and it also allows you to add in a
condition which can be used to filer the sequence. Your proposal
adds
>>nothing.

It does. Consider this:

whatever = [x for x in xrange(10000000 00) while x < 10]
That would run only in a splitsecond of what the whole listcomp
would.
>
Except that the comparable listcomp today is:

whatever = [x for x in takewhile(lambd a x: x < 10, xrange
(1000000000))]
>
which also runs in a split second.

Actually, the OP was correct, it does add something: it removes the
need
for a function or lambda in the takewhile just as the original
listcomp
removes a function or lambda compared with the map version.
Consider how it would be if the situation were reversed, and
whatever = [x for x in xrange(10000000 00) while x < 10] was the
convention today. What advantage would there be to replacing it with
whatever = [x for x in takewhile(lambd a x: x < 10, xrange(10000000 00))]?

As a newcomer to Python, I'd find the first syntax far more readily
graspable, and I'd have to wonder why I'd ever need takewhile and lambda
just to do what appears to be straightforward conditioning of a loop.

I'm not a newcomer to Python, and I wonder about that anyway.

I also note this, using Python 2.4.2 on win32:
>>whatever = [x for x in takewhile(lambd a x: x < 10, xrange
(1000000000))]
Traceback (most recent call last):
File "<stdin>", line 1, in ?
NameError: name 'takewhile' is not defined

So in addition to the two functions, I need an import statement. It
looks like the argument can certainly be made that simplifying the
syntax and lightening the call load bring some advantage to the table.
There are other arguments to be made against the proposed syntax, I'm
sure.

--
rzed

Aug 7 '06 #9

Eighty wrote:
I suggest a new extension of the list comprehension syntax:

[x for x in xs while cond(x)]

which would be equivalent to

list(itertools. takewhile(cond, xs))

+ Since Python favors list comprehensions over map, filter, and reduce,
this would be the preferred way to do this
+ "Takewhile operations" occur often, at least for me
+ I don't think it would break any existing syntax

An analogous syntax for dropwhile would be nice, but I can't think of
one.

This is not a PEP because it's a very simple idea and probably not just
anyone (read: me) can write and submit one. If there has been a PEP for
this, I've missed it; if not, it would be nice if someone wrote one.

Discuss.
So does no one have a comment on this? The one objection I can come up
with is that this would change the set builder notation semantics too
much, but since the iteration order in a list comprehension is already
well defined, I don't think that would be the case. However, for this
reason, it wouldn't fit in a dict comprehension, if that would ever be
made, perhaps making the syntax inconsistent?

Aug 8 '06 #10

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

Similar topics

15
1486
by: Adal Chiriliuc | last post by:
I think a function similar to the one below should be added to the builtin module: def boolselect(condition, trueresult, falseresult): if condition: return trueresult else: return falseresult --- WITH
11
1787
by: Paul Rubin | last post by:
I frequently find myself writing stuff like # compute frob function, x has to be nonnegative x = read_input_data() assert x >= 0, x # mis-use of "assert" statement frob = sqrt(x) + x/2. + 3. This is not really correct because the assert statement is supposed to validate the logical consistency of the program itself, not the input data. So, for example, when you compile with optimization on, assert
2
1708
by: Guido van Rossum | last post by:
Robert and Python-dev, I've read the J2 proposal up and down several times, pondered all the issues, and slept on it for a night, and I still don't like it enough to accept it. The only reason to accept it would be to pacify the supporters of the proposal, and that just isn't a good enough reason in language design. However, it got pretty darn close! I'm impressed with how the community managed to pull together and face the enormous...
15
2596
by: Ralf W. Grosse-Kunstleve | last post by:
****************************************************************************** This posting is also available in HTML format: http://cci.lbl.gov/~rwgk/python/adopt_init_args_2005_07_02.html ****************************************************************************** Hi fellow Python coders, I often find myself writing:: class grouping:
4
2737
by: wkaras | last post by:
I would like to propose the following changes to the C++ Standard, the goal of which are to provide an improved ability to specify the constraints on type parameters to templates. Let me say from the start that my knowledge of compiler implementation is very limited. Therefore, my suggestions may have to be rejected because they are difficult or impossible to implement. The proposal is based on the concept of "type similarity". Type...
0
1279
by: jygoh3 | last post by:
ENCYCLOPEDIA OF MOBILE COMPUTING & COMMERCE CALL FOR SHORT ARTICLES Proposal Deadline: 15 Nov 2005 (Extended)
47
3368
by: Pierre Barbier de Reuille | last post by:
Please, note that I am entirely open for every points on this proposal (which I do not dare yet to call PEP). Abstract ======== This proposal suggests to add symbols into Python. Symbols are objects whose representation within the code is more important than their actual value. Two symbols needs only to be
28
5799
by: kaferro | last post by:
What is the safest way to make an argv comparison? The code below works. #include <iostream> #include <string> using namespace std; int main(int argc, char *argv) {
56
6765
by: Adem | last post by:
C/C++ language proposal: Change the 'case expression' from "integral constant-expression" to "integral expression" The C++ Standard (ISO/IEC 14882, Second edition, 2003-10-15) says under 6.4.2(2) : case constant-expression : I propose that the case expression of the switch statement be changed from "integral constant-expression" to "integral expression".
0
9579
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
9416
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
10199
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8861
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
7393
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
6661
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
5293
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 the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5433
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2810
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.