473,386 Members | 1,883 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.

Is this a safe thing to do?

The following example works fine (Python 2.3), but is it always safe
to modify a list that is being iterated in a loop, regardless of the
actual contents of the list x? If not, what's a better (safe) way to
do it?

Thanks!

x=[{'f':9},{'f':1},{1:3,'f':9},{'f':3}]
for t in x: if t['f'] == 9:
x.remove(t)

x

[{'f': 1}, {'f': 3}]
Jul 18 '05 #1
4 1491
ph*****************@yahoo.com (Phil Schmidt) wrote in
news:22**************************@posting.google.c om:
The following example works fine (Python 2.3), but is it always safe
to modify a list that is being iterated in a loop, regardless of the
actual contents of the list x? If not, what's a better (safe) way to
do it?


No, it is never safe to do this, you might skip over list elements. For
example, a very small change to your data shows it going wrong:
x=[{'f':9},{'f':1},{1:3,'f':9},{'f':9},{'f':3}]
for t in x: if t['f'] == 9:
x.remove(t)

x [{'f': 1}, {'f': 9}, {'f': 3}]
The answer is to iterate over a COPY of the list if you want to modify it
during the iteration:
x=[{'f':9},{'f':1},{1:3,'f':9},{'f':9},{'f':3}]
for t in list(x): if t['f'] == 9:
x.remove(t)

x [{'f': 1}, {'f': 3}]


Copying the list may be done by using the 'list' builtin, by using an empty
slice, or using 'copy.copy'.

--
Duncan Booth du****@rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?
Jul 18 '05 #2
Phil Schmidt wrote:
The following example works fine (Python 2.3), but is it always safe
to modify a list that is being iterated in a loop, regardless of the
actual contents of the list x? If not, what's a better (safe) way to
do it?

Thanks!
x=[{'f':9},{'f':1},{1:3,'f':9},{'f':3}]
for t in x:
if t['f'] == 9:
x.remove(t)
x


[{'f': 1}, {'f': 3}]

This is generally not safe. Another way to do it is

x = filter(lambda t: t['f'] != 9, x)

which creates a new list out of all elements t satisfying t['f'] not
equal to 9, and then assigns the new list back to x.

David

Jul 18 '05 #3

"Duncan Booth" <du****@NOSPAMrcp.co.uk> wrote in message
news:Xn***************************@127.0.0.1...
The answer is to iterate over a COPY of the list if you want to modify it during the iteration:


or, when deleting items, carefully iterate backwards

x=[{'f':9},{'f':1},{1:3,'f':9},{'f':9},{'f':3}]
for i in range(len(x)-1,-1,-1):
if x[i]['f'] == 9:
del x[i]
x

[{'f': 1}, {'f': 3}]

Terry J. Reedy

Jul 18 '05 #4
ph*****************@yahoo.com (Phil Schmidt) wrote in message news:<22**************************@posting.google. com>...
The following example works fine (Python 2.3), but is it always safe
to modify a list that is being iterated in a loop, regardless of the
actual contents of the list x? If not, what's a better (safe) way to
do it?

Thanks!

x=[{'f':9},{'f':1},{1:3,'f':9},{'f':3}]
for t in x: if t['f'] == 9:
x.remove(t)

x [{'f': 1}, {'f': 3}]


This is the perfect place to use a list comprehension:
x=[{'f':9},{'f':1},{1:3,'f':9},{'f':3}]
x = [t for t in x if t['f'] != 9]
x [{'f': 1}, {'f': 3}]

Jul 18 '05 #5

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

Similar topics

42
by: Irmen de Jong | last post by:
Pickle and marshal are not safe. They can do harmful things if fed maliciously constructed data. That is a pity, because marshal is fast. I need a fast and safe (secure) marshaler. Is xdrlib the...
3
by: Job Lot | last post by:
I am having loads of problem using vb.net project under visual source safe. I’ll start with How can I exclude source safe information from the project when I take a copy of project home? I...
21
by: Nitin Bhardwaj | last post by:
Hi all, It is said that C++ is a strongly typed language and thus a type-safe language (unlike C). So how does one explain the following behaviour : int main(void) { char *p = NULL; p = "A...
5
by: nicolas_riesch | last post by:
Does someone know if the module pytz (http://sourceforge.net/projects/pytz/) is thread-safe ? I have not seen it explicitely stated, and just wanted to be sure, as I want to use it. That's...
26
by: 69dbb24b2db3daad932c457cccfd6 | last post by:
Hello, I have to initialize all elements of a very big float point array to zero. It seems memset(a, 0, len) is faster than a simple loop. I just want to know whether it is safe to do so, since I...
8
by: ais523 | last post by:
I use this function that I wrote for inputting strings. It's meant to return a pointer to mallocated memory holding one input string, or 0 on error. (Personally, I prefer to use 0 to NULL when...
95
by: hstagni | last post by:
Where can I find a library to created text-based windows applications? Im looking for a library that can make windows and buttons inside console.. Many old apps were make like this, i guess ...
1
by: kiluyar | last post by:
I have such a function: class T { public: T(){...//some operations} }; T& GetInst()
51
by: James Harris | last post by:
If in C one codes a function which includes return a++; does 'a' get incremented? Would the behaviour be safe to rely upon? I guess this might apply if 'a' were static or such as return...
3
by: =?Utf-8?B?anBhdHJjaWs=?= | last post by:
Don't see any official notice that compiled library dll's loaded in the BIN directory of an asp.net website need to be thread safe, but concurrent visits to the same web site sure bear this out....
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
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
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
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...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
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
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.