473,698 Members | 2,186 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

iterating over collection, deleting entries

I want to iterate over a collection and delete all unwanted entries.

for item in collection:
del item

of course doesn´t do anything useful. Two things come to mind:
a) iterating backwards over the collection using indexing, something like:

for i in range(len(colle ction)-1, -1, -1):
item = collection[i]
if isBad(item) del collection[i]

b) duplicating the collection, iterating over one and deleting from the
other.

Both solutions seem both ugly and expensive to me, solution a)
probably isn´t even O(x) anymore.

Please tell me, what´s the best way to do this?
--
Patrick von Harsdorf
pa*****@harsdor f.de


Jul 18 '05 #1
3 1817
Sorry, I missed that SnuSnu just posed a very similar question.
Please ignore my post...
Jul 18 '05 #2
On Sun, 25 Apr 2004 18:25:08 +0200, "Patrick von Harsdorf"
<pa*****@harsdo rf.de> wrote:
Please tell me, what´s the best way to do this?


I'm pretty new to python, but normally this is done
by a simple read-write approach. You iterate over
the elements using a "read" pointer, and every time
you find one you want to keep you just write it
and increment the write pointer.
In code...

wrp = 0

for x in container:
if is_good(x):
container[wrp] = x
wrp += 1

del container[wrp:]

This is O(n) and doesn't require any additional memory

I suppose however that it's not so common finding
cases in which this is much better than...

a = [x for x in a if is_good(x)]

The latter will allocate a list for the result
(instead of reusing the same), but can free the
original (and this may be *better* than just
resizing it - it may be better in C++, for example).

HTH
Andrea
Jul 18 '05 #3
I would do:

collection=[i for i in collection if not isBad(i)]

Larry Bates
Syscon, Inc.
"Patrick von Harsdorf" <pa*****@harsdo rf.de> wrote in message
news:c6******** *****@news.t-online.com...
I want to iterate over a collection and delete all unwanted entries.

for item in collection:
del item

of course doesn´t do anything useful. Two things come to mind:
a) iterating backwards over the collection using indexing, something like:

for i in range(len(colle ction)-1, -1, -1):
item = collection[i]
if isBad(item) del collection[i]

b) duplicating the collection, iterating over one and deleting from the
other.

Both solutions seem both ugly and expensive to me, solution a)
probably isn´t even O(x) anymore.

Please tell me, what´s the best way to do this?
--
Patrick von Harsdorf
pa*****@harsdor f.de

Jul 18 '05 #4

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

Similar topics

4
1460
by: Saso Zagoranski | last post by:
Hi! I need an array-type of collection when the entries would look like: object myObject, int myInt, string myString Which collection should I use? I know I could declare a multidimensional array of objects but adding and deleting to that array would require distribution of objects each time something was deleted or added so
1
2165
by: Josema | last post by:
Hi, My problem is the next one (in a windows application): - I have a class derived from collectionbase to fill with persons object (id, name) from database. - I have a ListBox wich datasource its the collectionbase above. I want to do: - I would like that when i click in a item of the listbox, deletes from database the values of this item, and from collection too. Then refresh the listbox with the collection modified.
8
1128
by: orekin | last post by:
Hi There I have a huge array of objects being displayed on a UI. These are actually 'jobs' that the users need to deal with before close of business. As the operator deals with a particular job, I want to add the unique identifier for that job to a collection. The collection simply keeps track of jobs that have been dealt with.
10
15129
by: Ken Foster | last post by:
I have a hashtable keyed by some name, holding an instance of an object. Most of the time I use the hashtable in the traditional sense, given a name, I lookup the object, then I run a method on that object. Occaisionally however I need to run a method on every object in the hashtable. I've done both For..Each and iEnumeratior loops. The messy part is that under certain conditions, while iterating, a condition exists where I need to remove...
1
4506
by: Martin Widmer | last post by:
Hi Folks. When I iterate through my custom designed collection, I always get the error: "Unable to cast object of type 'System.Collections.DictionaryEntry' to type 'ContentObjects.ContentBlock'." The error occurs at the "For...Each" line if this method:
5
3988
by: Manish | last post by:
The topic is related to MySQL database. Suppose a table "address" contains the following records ------------------------------------------------------- | name | address | phone | ------------------------------------------------------- | mr x | 8th lane | 124364 | | mr x | 6th lane | 435783 | | mrs x | 6th lane | 435783 |
5
12126
by: Alan | last post by:
I was wondering whether it is good programming practice or asking for trouble to modify a vector while iterating through it. That is, I want to do something like the following pseudocode in C++: for each element of the vector for each subsequent element of the vector if the belong together <some code to compare them> then merge the elements (add the 2nd to the 1st, then delete the 1st)
5
1958
by: mikehulluk | last post by:
Ok, Imagine I have a class class C { }; ostream& operator<<(ostream& o, const C& c) { ...}
3
1223
by: Bob Altman | last post by:
Hi all, I read somewhere that the STL map class stores entries internally sorted by the key. I wrote a small test program (below) that verifies that iterating through the map returns entries with ascending key values. My question is: Is this guaranteed behavior or is it just the current implementation which might change in the future? TIA - Bob
0
8674
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
9157
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
9028
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...
0
8861
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
7728
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...
0
5860
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
4369
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
4619
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2330
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.