I posted this code last night in response to another thread, and after I
posted it I got to wondering if I had misused the list comprehension. Here's
the two examples:
Example 1:
--------------------
def compress(s):
new = []
for c in s:
if c not in new:
new.append(c)
return ''.join(new)
----------------------
Example 2:
------------------------
def compress(s):
new = []
[new.append(c) for c in s if c not in new]
return ''.join(new)
--------------------------
In example 1, the intention to make an in-place change is explicit, and it's
being used as everyone expects it to be used. In example 2, however, I began
to think this might be an abuse of list comprehensions, because I'm not
assigning the result to anything (nor am I even using the result in any
way).
What does everyone think about this? Should list comprehensions be used this
way, or should they only be used to actually create a new list that will
then be assigned to a variable/returned/etc.?
Jun 27 '08
31 1226
On Tue, May 27, 2008 at 8:08 PM, Gabriel Genellina
<ga*******@yaho o.com.arwrote:
En Tue, 27 May 2008 14:43:52 -0300, Ian Kelly <ia*********@gm ail.com>
escribió:
>It sounds like the wasteful list creation is the biggest objection to using a list comprehension. I'm curious what people think of this alternative, which avoids populating the list by using a generator expression instead (apart from the fact that this is still quadratic, which I'm aware of).
def compress(s): new = [] filter(None, (new.append(c) for c in s if c not in new)) return ''.join(new)
filter returns a newly created list, so this code is as wasteful as a list
comprehension (and harder to read).
Here it returns a newly created *empty* list, which is not nearly as
wasteful as one that's linear in the size of the input. I'll grant
you the second point, though. I very much doubt that I would ever
actually use this myself. I was just curious what others would think
of it.
On May 20, 8:51*pm, "Diez B. Roggisch" <de...@nospam.w eb.dewrote:
bearophileH...@ lycos.com wrote:
John Salerno:
What does everyone think about this?
The Example 2 builds a list, that is then thrown away. It's just a
waste of memory (and time).
No, it doesn't. It uses append because it refers to itself in the
if-expression. So the append(c) is needed - and thus the assignment
possible but essentially useless.
Diez
Yes it does, it build a list of 'None's.
And if list.append is concerned, the example given has no use, since:
x = [c for c in cs]
is essentially the same as
x = []
[x.append(c) for c in cs]
If, you're talking about other function calls, it might be an abuse or
not depending on personal preference. This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
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 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: ]++x for x in partitions(n-k) for k in
range(1,n)]
As defined...
|
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...
|
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 faster than map. This speed
difference owes to the fact that map and list comprehensions run at C...
|
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):
|
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
--
| |
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, chr(65+i)) for i in range(4))
>
> Sure, but the same holds for list comprehensions: list(i*i for i in
|
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, or
actually making "_" a list of lists and using the real first, second,
third elements? This is...
|
by: Delaney, Timothy (Tim) |
last post by:
Ian Kelly wrote:
Are you aware that filter() returns a list populated from its arguments?
Tim Delaney
|
by: Ian Kelly |
last post by:
On Tue, May 27, 2008 at 7:09 PM, Delaney, Timothy (Tim)
<tdelaney@avaya.comwrote:
Yes. In this case, it returns an empty list.
|
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...
|
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...
| |
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,...
|
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...
|
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...
|
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();...
|
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...
|
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
| |
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...
| |