473,386 Members | 1,752 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

properly delete item during "for item in..."

Say you have something like this:

for item in myList:
del item

Would this actually delete the item from the list or just decrement
the reference counter because the item in myList is not associated
with name "item" anymore (but still is with myList[itemIndex])? In
other words, is "item" a temporary reference to myList[itemIndex] or
is it actually that reference that myList has stored?

I am not sure if this question even makes any sense anymore. I've been
using python for years and never had any problems (and I don't now
either) but now that I had to revisit c++/STL, I had to deal about
these issues and was wondering how python does it.

Thanks,
Ratko
Jul 17 '08 #1
8 1692
On Thu, 17 Jul 2008 09:27:27 -0700, Ratko wrote:
for item in myList:
del item

Would this actually delete the item from the list or just decrement
the reference counter because the item in myList is not associated
with name "item" anymore (but still is with myList[itemIndex])? In
other words, is "item" a temporary reference to myList[itemIndex] or
is it actually that reference that myList has stored?
The latter. Names are always bound to objects, you can't bind a name to
another name or reference in Python.

Ciao,
Marc 'BlackJack' Rintsch
Jul 17 '08 #2
Ratko wrote:
Say you have something like this:

for item in myList:
del item

Would this actually delete the item from the list or just decrement
the reference counter because the item in myList is not associated
with name "item" anymore (but still is with myList[itemIndex])? In
other words, is "item" a temporary reference to myList[itemIndex] or
is it actually that reference that myList has stored?
The 'del' statement does not delete an object, it deletes a reference to
an object. In this case, the variable item is deleted from the scope,
and the referred-to object will have its reference counter decremented
by 1. (But, as you surmise, not to zero, because the list will still
reference it.)

You could remove the object from the list with
del myList[i]
if you knew i. HOWEVER, don't do that while looping through the list!
Changing a list's length will interact badly with the for loop's
indexing through the list, causing the loop to mis the element following
the deleted item.

Gary Herron
I am not sure if this question even makes any sense anymore. I've been
using python for years and never had any problems (and I don't now
either) but now that I had to revisit c++/STL, I had to deal about
these issues and was wondering how python does it.

Thanks,
Ratko
--
http://mail.python.org/mailman/listinfo/python-list
Jul 17 '08 #3
mk
Gary Herron wrote:
You could remove the object from the list with
del myList[i]
if you knew i. HOWEVER, don't do that while looping through the list!
Changing a list's length will interact badly with the for loop's
indexing through the list, causing the loop to mis the element following
the deleted item.
Jumping into a thread, I know how not to do it, but not how to do it
properly?

Iterating over a copy may _probably_ work:
>>t=['a', 'c', 'b', 'd']

for el in t[:]:
del t[t.index(el)]

>>t
[]
However, is it really safe? Defining safe as "works reliably in every
corner case for every indexable data type"?
Con: suppose the data structure t is really, really big. Just deleting
some items from t temporarily doubles the memory consumption.

Jul 17 '08 #4
On Jul 17, 9:57 am, mk <mrk...@gmail.comwrote:
Gary Herron wrote:
You could remove the object from the list with
del myList[i]
if you knew i. HOWEVER, don't do that while looping through the list!
Changing a list's length will interact badly with the for loop's
indexing through the list, causing the loop to mis the element following
the deleted item.

Jumping into a thread, I know how not to do it, but not how to do it
properly?

Iterating over a copy may _probably_ work:
>>t=['a', 'c', 'b', 'd']
>>>
>>for el in t[:]:
del t[t.index(el)]
>>t
[]

However, is it really safe? Defining safe as "works reliably in every
corner case for every indexable data type"?

Con: suppose the data structure t is really, really big. Just deleting
some items from t temporarily doubles the memory consumption.


Would this work (safely) then? It does in my test cases but that of
course doesn't prove it works in a general case...

for item in myList:
myList.remove(item)
For dictionaries we can just iterate over values() or items() as
opposed to itervalues() or iteritems() since that's technically a copy
of values or items in the dict, right?
R

Jul 17 '08 #5
mk <mr****@gmail.comwrote:
Iterating over a copy may _probably_ work:
>t=['a', 'c', 'b', 'd']

for el in t[:]:
del t[t.index(el)]

>t
[]
However, is it really safe? Defining safe as "works reliably in every
corner case for every indexable data type"?
No, because you cannot necessarily copy every indexable data type using
t[:], and not all types will support index. Also it is inefficient to
delete from the start of the list.

If you are working with a list and deleting every object:

del t[:]

will suffice.

If you don't want to delete everything then you could do:

for index, el in enumerate(reversed(t)):
if not wewant(el):
del t[index]

but the pythonic way is just:

t[:] = [ el for el in t if wewant(el) ]

or if you just want the filtered list and don't care about updating the
original:

t = [ el for el in t if wewant(el) ]

Con: suppose the data structure t is really, really big. Just deleting
some items from t temporarily doubles the memory consumption.
No it doesn't. Copying a list doesn't copy any of the elements in the list,
it just copies the references to those element.
Jul 17 '08 #6
Ratko wrote:
On Jul 17, 9:57 am, mk <mrk...@gmail.comwrote:
>Gary Herron wrote:
>>You could remove the object from the list with
del myList[i]
if you knew i. HOWEVER, don't do that while looping through the list!
Changing a list's length will interact badly with the for loop's
indexing through the list, causing the loop to mis the element following
the deleted item.
Jumping into a thread, I know how not to do it, but not how to do it
properly?

Iterating over a copy may _probably_ work:
> >>t=['a', 'c', 'b', 'd']

for el in t[:]:
del t[t.index(el)]
> >>t
[]

However, is it really safe? Defining safe as "works reliably in every
corner case for every indexable data type"?

Con: suppose the data structure t is really, really big. Just deleting
some items from t temporarily doubles the memory consumption.

Would this work (safely) then? It does in my test cases but that of
course doesn't prove it works in a general case...

for item in myList:
myList.remove(item)
No. Same problem, The for loop iterates through the list by keeping
and incrementing an internal index. Any modification of the list does
not change the index correspondingly.

One proper way:
newList = []
for item in myList:
if ... whatever...
newList.append(item)
myList = newList

Another, using list comprehension (it's the same thing really as the above):
myList = [item for item in myList if ... whatever...]

>
For dictionaries we can just iterate over values() or items() as
opposed to itervalues() or iteritems() since that's technically a copy
of values or items in the dict, right?
No! In fact the whole point of iteritems and itervalues and iterkeys is
that they *DO NOT* make copies, so changing the dictionary out from
under them is a programming error.

If you use dict.items(), dict.keys() or dict.values(), then you're OK,
because these methods *do* create new lists for both.

Gary Herron
>
R

--
http://mail.python.org/mailman/listinfo/python-list
Jul 17 '08 #7
For dictionaries we can just iterate over values() or items() as
opposed to itervalues() or iteritems() since that's technically a copy
of values or items in the dict, right?

No! In fact the whole point of iteritems and itervalues and iterkeys is
that they *DO NOT* make copies, so changing the dictionary out from
under them is a programming error.

If you use dict.items(), dict.keys() or dict.values(), then you're OK,
because these methods *do* create new lists for both.

That's what I meant, it just didn't come across correctly I guess.
Thanks for clarifying these issues. I think I have a better
understanding now.
R
Jul 17 '08 #8

-----Original Message-----
From: py********************************@python.org [mailto:python-
li*************************@python.org] On Behalf Of Ratko
Sent: Thursday, July 17, 2008 12:27 PM
To: py*********@python.org
Subject: properly delete item during "for item in..."

Say you have something like this:

for item in myList:
del item

Would this actually delete the item from the list or just decrement
the reference counter because the item in myList is not associated
with name "item" anymore (but still is with myList[itemIndex])? In
other words, is "item" a temporary reference to myList[itemIndex] or
is it actually that reference that myList has stored?

I am not sure if this question even makes any sense anymore. I've been
using python for years and never had any problems (and I don't now
either) but now that I had to revisit c++/STL, I had to deal about
these issues and was wondering how python does it.

Walk the list backwards when deleting.

master = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
print "Deletes nothing"
a = master[:]
print a
for i in a:
del i
print a

print
print

print "Deletes safely from end"
a = master[:]
print a
for i in range(len(a)-1, -1, -1):
print i
if i % 2 == 0:
print " removing ", master[i]
del a[i]
print " ", a,
if master[i] in a:
print "Ooops, deleted wrong thing...",
print
print a

print
print

print "Delete from front. Deletes wrong things and throws an
exception..."
a = master[:]
print a
#for i in range(len(a)-1, -1, -1):
for i in range(len(a)):
print i
if i % 2 == 0:
print " removing ", master[i]
del a[i]
print " ", a,
if master[i] in a:
print "Ooops, deleted wrong thing...",
print
print a
Jul 17 '08 #9

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

Similar topics

3
by: maadhuu | last post by:
well,i am curious to know what would be the output of the following: delete this; basically , comment on this .
6
by: RSB | last post by:
Hi Everyone, i am using a ASP: DataGrid control in the page and for each row i have a Delete Button Column. Every thing works fine. But now i want to add a Java script confirmation check for the...
0
by: lanmou | last post by:
hi, I have a listbox whose datasource property is set.i would like to delete the item from the listbox after the records of that item are deleted from the database.the selecteditem.clear or refresh...
2
blyxx86
by: blyxx86 | last post by:
I am trying to find a method of allowing users to 'delete' data from the database, but without that information actually being deleted. Is there a possibility of some sort of code or macro that...
1
by: =?Utf-8?B?ZGg=?= | last post by:
The code below hung during execution at "File.Delete(testFile)"... if (File.Exists(testFile)) { Console.WriteLine("Before jumping off the cliff..."); File.Delete(testFile); } ...
1
by: pilafi | last post by:
void CSVImageIO::Read( void * buffer) { char onedataline; char *tmp=0; double d=0; unsigned short data=0; unsigned short * inptr = static_cast< unsigned short * >( buffer ); unsigned...
1
by: D. Susman | last post by:
Hi, When I call "clean" as shown below, shouldn't I be getting segmentation fault due to garbage data? I am compiling with CC and the output is 5. Does "delete" not delete in this situation or...
30
by: Medvedev | last post by:
i see serveral source codes , and i found they almost only use "new" and "delete" keywords to make they object. Why should i do that , and as i know the object is going to be destroy by itself at...
3
by: tvnaidu | last post by:
I compiled tinyxml files (.cpp files) and when I am linking to create final exe in Linux, I am getting lot of errors saying "undefiend reference" to "operator new" and "delete", any idea?. ...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
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
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...
0
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,...
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...

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.