473,471 Members | 1,896 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

deleting items within a for loop - mutable indices

Okay - here's a (probably) really easy question:

I can't do the following, so what's the best way to handle this
case of wanting to delete within a loop?

x = [0,1,2,3,4,5,6,7,8]
deletion_list = [2,7,8]

for i in deletion_list:
del x[i]

This obviously doesn't work because the list keeps changing
each time I delete something, so the indices are no longer valid
after the first delete (so I get an IndexError on teh last delete).

My hack is to do this first (which makes sure that the higher indices
are deleted first), but this is not very elegant or quick:

deletion_list.sort()
deletion_list.reverse()
# BTW: It's a shame I can't do deletion_list.sort().reverse()

Is there a simple solution?

(It would be nice to do something like
del x[2,7,8] # or..
del [*deletion_list]
)

Thanks.

Jul 18 '05 #1
6 1512
SnuSnu wrote:
Okay - here's a (probably) really easy question:

I can't do the following, so what's the best way to handle this
case of wanting to delete within a loop?

x = [0,1,2,3,4,5,6,7,8]
deletion_list = [2,7,8]

for i in deletion_list:
del x[i]

This obviously doesn't work because the list keeps changing
each time I delete something, so the indices are no longer valid
after the first delete (so I get an IndexError on teh last delete).
The solution is usually to either iterate over an explicit copy of the
list, or use functional means to build the final list up from the
original list without mutating it at all.

In this case it's probably best to just iterate backwards over the
indices, since you know what you're getting and can control the order in
which you delete the items.
deletion_list.sort()
deletion_list.reverse()
# BTW: It's a shame I can't do deletion_list.sort().reverse()


This is a deliberate design decision. These methods are made to return
None so you're explicitly aware that they mutate the object, rather than
return a duplicate. You can always define your own functional version:

def mySort(seq):
result = seq[:]
result.sort()
return result

--
__ Erik Max Francis && ma*@alcyone.com && http://www.alcyone.com/max/
/ \ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis
\__/ Awards are merely the badges of mediocrity.
-- Charles Ives
Jul 18 '05 #2
SnuSnu <sn****@tiscali.co.uk> wrote in message news:<40**********@mk-nntp-2.news.uk.tiscali.com>...
Okay - here's a (probably) really easy question:

I can't do the following, so what's the best way to handle this
case of wanting to delete within a loop?

x = [0,1,2,3,4,5,6,7,8]
deletion_list = [2,7,8]

for i in deletion_list:
del x[i]

This obviously doesn't work because the list keeps changing
each time I delete something, so the indices are no longer valid
after the first delete (so I get an IndexError on teh last delete).


for i in deletion_list:
x[i] = None
x = [num for num in x if num is not None]
Jul 18 '05 #3
SnuSnu <sn****@tiscali.co.uk> wrote in message news:<40**********@mk-nntp-2.news.uk.tiscali.com>...
Okay - here's a (probably) really easy question:

I can't do the following, so what's the best way to handle this
case of wanting to delete within a loop?

x = [0,1,2,3,4,5,6,7,8]
deletion_list = [2,7,8]

for i in deletion_list:
del x[i]

This obviously doesn't work because the list keeps changing
each time I delete something, so the indices are no longer valid
after the first delete (so I get an IndexError on teh last delete).

My hack is to do this first (which makes sure that the higher indices
are deleted first), but this is not very elegant or quick:

deletion_list.sort()
deletion_list.reverse()
# BTW: It's a shame I can't do deletion_list.sort().reverse()

Is there a simple solution?

(It would be nice to do something like
del x[2,7,8] # or..
del [*deletion_list]
)

Thanks.


Eh, do you want to delete the elements in the deletion list from x, or
delete the elements in x which are at the location indicated in the
deletion list? Your example doesn't differentiate.

Anyhow, this is advice from a newbie :-) but in the first case

x = [y for y in x if not y in deletion_list]

works well enough.

otherwise

tmp = [x[i] for i in range(len(x)) if not i in deletion_list]
x = tmp

you could speed either up for largish lists with hashing;

dict = {}
for d in deletion_list:
dict[d] = 1
tmp = [x[i] for i in range(len(x)) if not dict.has_key(i)]
x = tmp

alternatively you could make it linear in time for the number of
deletion elements, but the performance hit from creating a bunch of
lists hurts a bit too much, unless you don't care about order. Which
I'm guessing you do.

Jam
Jul 18 '05 #4
SnuSnu wrote:
are deleted first), but this is not very elegant or quick:


Here is a list comprehension that makes a new list
without the deletion_list items. It does have the virtue
of being a one liner :-)

newx=[x[i] for i in range(len(x)) if i not in deletion_list]

You will need to do timings to see what method is actually
the fastest. Don't forget to do so with list sizes the
same as you expect to be using in your real program. Search
archives for this group for 'timeit' to see examples of
how to do timings.

(I think that the size of the deletion_list as a proportion
of the original list is what best determines the relative
speeds of the various methods available).

Roger
Jul 18 '05 #5
Hello,

this should work:

for i in deletion_list:
x.remove(i)

Matuka

"SnuSnu" <sn****@tiscali.co.uk> wrote in message
news:40**********@mk-nntp-2.news.uk.tiscali.com...
Okay - here's a (probably) really easy question:

I can't do the following, so what's the best way to handle this
case of wanting to delete within a loop?

x = [0,1,2,3,4,5,6,7,8]
deletion_list = [2,7,8]

for i in deletion_list:
del x[i]

This obviously doesn't work because the list keeps changing
each time I delete something, so the indices are no longer valid
after the first delete (so I get an IndexError on teh last delete).

My hack is to do this first (which makes sure that the higher indices
are deleted first), but this is not very elegant or quick:

deletion_list.sort()
deletion_list.reverse()
# BTW: It's a shame I can't do deletion_list.sort().reverse()

Is there a simple solution?

(It would be nice to do something like
del x[2,7,8] # or..
del [*deletion_list]
)

Thanks.

Jul 18 '05 #6
James Moughan wrote:
you could speed either up for largish lists with hashing;

dict = {}
for d in deletion_list:
dict[d] = 1
tmp = [x[i] for i in range(len(x)) if not dict.has_key(i)]
x = tmp


If order doesn't matter and the items are unique you may wish to use
sets.Set from python 2.3 instead of a dict:
from sets import Set
set = Set(['a', 'b', 2, 42])
for item in deletion_list: .... set.discard(item)
.... print set

Set(['b', 42])

--
Steven Rumbalski
news AT rumbalski DOT com
Jul 18 '05 #7

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

Similar topics

12
by: Steven Bethard | last post by:
So I need to do something like: for i in range(len(l)): for j in range(i+1, len(l)): # do something with (l, l) where I get all pairs of items in a list (where I'm thinking of pairs as sets,...
5
by: andrea.gavana | last post by:
Hello NG, I was wondering if there is a faster/nicer method (than a for loop) that will allow me to find the elements (AND their indices) in a list that verify a certain condition. For example,...
5
by: Steven Bethard | last post by:
So, I have a list of lists, where the items in each sublist are of basically the same form. It looks something like: py> data = , .... .... , .... .... ] Now, I'd like to...
14
by: Matthew Wells | last post by:
I'm using this code to delete all relationships in my mdb file iFlag = 1 Do While iFlag <> 0 iFlag = 0 For Each rel In db.Relations db.Relations.Delete rel.Name iFlag = 1 Next rel Loop
1
by: Crash | last post by:
Windows XP SP2 C# .NET v1.1 Outlook 2003 {via Office 11.0 PIA} I'm manipulating Outlook's calendar via OLE automation from my C# application. I would like to iterate through the calendar items...
1
by: Tim | last post by:
Hi, I'm very new to .NET and am programming in C#. I have a web application where i have two list boxes. Its kind of like a shopping card where you can add items from one 'locations' list box to...
5
by: Phill W. | last post by:
(VB'2003) What's the correct way to remove multiple, selected items from a ListView control (say, from a ContextMenu)? I ask because I'm getting a very annoying ArgumentOutOfRangeException...
9
by: Rhamphoryncus | last post by:
The problems of this are well known, and a suggestion for making this easier was recently posted on python-dev. However, I believe this can be done just as well without a change to the language. ...
7
by: Ivan Voras | last post by:
For a declaration like: List<MyTypeitems = ... where MyType is a struct, attempt to modify an item with items.member = something; fails with the message:
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
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...
1
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...
1
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...
0
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...
0
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...
0
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
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 ...

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.