473,417 Members | 1,555 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,417 software developers and data experts.

modifying mutable list elements in a for loop

Whew. I hope that title is descriptive!

Hi all,

The python tutorial tells me "It is not safe to modify the sequence
being iterated over in the loop". But what if my list elements are
mutable, such as lists or objects, e.g.

a = [[1,2], [3,4], [5,6], [7,8]]
for coord in a:
coord.append(10)
print str(a)

When I tried it, it gave the "expected" answer, i.e.

[[1, 2, 10], [3, 4, 10], [5, 6, 10], [7, 8, 10]]

It worked, but is it safe? I can't see why it wouldn't be, but
technically I have broken the rules because I have modified the
sequence which is being looped over.

[It seems to me that the list elements are pointers (in C-speak), so I
can safely modify the data they are pointing to, because I am not
modifying the list elements themselves. Or is that an implementation
detail (i.e. not safe)?]

Actually the more I think about it the more I think it must be OK,
because how else can one perform an operation on a list of objects?
But that phrase "It is not safe to modify the sequence being iterated
over in the loop" in the tutorial has me slightly worried.

--
Regards,

Peter Ballard
Adelaide, AUSTRALIA
pb******@ozemail.com.au
http://members.ozemail.com.au/~pballard/
Jul 18 '05 #1
6 5022
Peter Ballard wrote:
The python tutorial tells me "It is not safe to modify the sequence
being iterated over in the loop". But what if my list elements are
mutable, such as lists or objects, e.g.
Treat that as "not safe if you don't know what you are doing".
David's answer is on the mark, but furthermore you *can* modify
the sequence being iterated over, if that's really what you
want to do. Some algorithms can probably even benefit from the
technique, though I can't think of anything off-hand.

As with many things in Python, consenting adults can do what they
want, and the tutorial is just giving a necessary warning since
many beginners, and even non-beginners from time to time, will be
caught by this problem otherwise.
[It seems to me that the list elements are pointers (in C-speak), so I
can safely modify the data they are pointing to, because I am not
modifying the list elements themselves. Or is that an implementation
detail (i.e. not safe)?]
It's safe. And around here they're usually called "references" instead
of "pointers".
But that phrase "It is not safe to modify the sequence being iterated
over in the loop" in the tutorial has me slightly worried.


Good. ;-) Then you'll have to pause and think about it from time to
time as you learn, until you've integrated the knowledge so deeply
that you automatically do the right thing when iterating over lists.
That's the goal of that warning in the tutorial (if I may channel the
author for a moment :-).

-Peter
Jul 18 '05 #2
Peter Ballard wrote:
Whew. I hope that title is descriptive!

Hi all,

The python tutorial tells me "It is not safe to modify the sequence
being iterated over in the loop". But what if my list elements are
mutable, such as lists or objects, e.g.

a = [[1,2], [3,4], [5,6], [7,8]]
for coord in a:
coord.append(10)
print str(a)

When I tried it, it gave the "expected" answer, i.e.

[[1, 2, 10], [3, 4, 10], [5, 6, 10], [7, 8, 10]]

It worked, but is it safe? I can't see why it wouldn't be, but
technically I have broken the rules because I have modified the
sequence which is being looped over.


You're fine. You didn't modify the sequence a, but other objects which
happened to be in the sequence. What the tutorial warns you against is
doing something like a.append([]) or a.pop() in your loop. Then you'd be
modifying the sequence itself.

--
Shalabh
Jul 18 '05 #3
If you write this as a list comprehension it "seems"
more safe (and clear to me at least):

a = [[1,2], [3,4], [5,6], [7,8]]
a = [x+[10] for x in a]

Larry Bates
Syscon, Inc.

"Peter Ballard" <pb******@ozemail.com.au> wrote in message
news:9d*************************@posting.google.co m...
Whew. I hope that title is descriptive!

Hi all,

The python tutorial tells me "It is not safe to modify the sequence
being iterated over in the loop". But what if my list elements are
mutable, such as lists or objects, e.g.

a = [[1,2], [3,4], [5,6], [7,8]]
for coord in a:
coord.append(10)
print str(a)

When I tried it, it gave the "expected" answer, i.e.

[[1, 2, 10], [3, 4, 10], [5, 6, 10], [7, 8, 10]]

It worked, but is it safe? I can't see why it wouldn't be, but
technically I have broken the rules because I have modified the
sequence which is being looped over.

[It seems to me that the list elements are pointers (in C-speak), so I
can safely modify the data they are pointing to, because I am not
modifying the list elements themselves. Or is that an implementation
detail (i.e. not safe)?]

Actually the more I think about it the more I think it must be OK,
because how else can one perform an operation on a list of objects?
But that phrase "It is not safe to modify the sequence being iterated
over in the loop" in the tutorial has me slightly worried.

--
Regards,

Peter Ballard
Adelaide, AUSTRALIA
pb******@ozemail.com.au
http://members.ozemail.com.au/~pballard/

Jul 18 '05 #4

"Peter Ballard" <pb******@ozemail.com.au> wrote in message
news:9d*************************@posting.google.co m...
The python tutorial tells me "It is not safe to modify the sequence
being iterated over in the loop".


What is not safe *in general* is adding and subtracting items to and from
the list while traversing it, either directly or indirectly (via an index
variable). There are exceptions, but they may or may not be
implementation dependent (I would have to read the standard more closely to
say more), and should only be used by people who understand them.

What is safe is modifying or replacing the 'current' item. The former is
easy. The latter requires the item index, as in 'for i in range(l): l[i] =
f(l[i])' (in-place map) -- but here, the iteration list isnt the list being
modified! (nor is it with enumerate()!)

Terry J. Reedy


Jul 18 '05 #5
On Wed, 26 May 2004 09:37:54 -0400, Peter Hansen <pe***@engcorp.com>
wrote:
Peter Ballard wrote:
The python tutorial tells me "It is not safe to modify the sequence
being iterated over in the loop". But what if my list elements are
mutable, such as lists or objects, e.g.


Treat that as "not safe if you don't know what you are doing".
David's answer is on the mark, but furthermore you *can* modify
the sequence being iterated over, if that's really what you
want to do.


OTOH:

d={"a":1,"b":2}
for k in d:
d.pop(k)

results in:

RuntimeError: dictionary changed size during iteration

I don't recall why I ran into this. But was mildly surprised.

Art

Jul 18 '05 #6
Arthur wrote:
On Wed, 26 May 2004 09:37:54 -0400, Peter Hansen wrote:
Treat that as "not safe if you don't know what you are doing".
David's answer is on the mark, but furthermore you *can* modify
the sequence being iterated over, if that's really what you
want to do.


OTOH:

d={"a":1,"b":2}
for k in d:
d.pop(k)

results in:

RuntimeError: dictionary changed size during iteration

I don't recall why I ran into this. But was mildly surprised.


Interesting, but on second thought quite logical I think.
After all, dictionaries are not *sequences*, so there is
no defined order in which to iterate over their keys, so
changes would have undefined results unless a copy was made
of the keys at the start of the loop. I suspect that
wasn't done because it would waste memory and time and
the only benefit would be allowing in-loop modifications.

Iterating over a sequences, on the other hand, is handled
in a clearly defined fashion and therefore modifications
to the sequence can be done during the loop if that makes
sense (though mostly it doesn't).

-Peter
Jul 18 '05 #7

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

Similar topics

17
by: Gordon Airport | last post by:
Has anyone suggested introducing a mutable string type (yes, of course) and distinguishing them from standard strings by the quote type - single or double? As far as I know ' and " are currently...
23
by: Fuzzyman | last post by:
Pythons internal 'pointers' system is certainly causing me a few headaches..... When I want to copy the contents of a variable I find it impossible to know whether I've copied the contents *or*...
9
by: Jess Austin | last post by:
hi, I like the way that Python does lists, and I love the way it does iterators. But I've decided I don't like what it does with iterators of lists. Lists are supposed to be mutable sequences,...
6
by: SnuSnu | last post by:
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 = deletion_list = for i in...
18
by: Markus.Elfring | last post by:
The C++ language specification provides the key word "mutable" that is not available in the C99 standard. Will it be imported to reduce any incompatibilities?...
5
by: Ken Schutte | last post by:
Hi, I'm been trying to create some custom classes derived from some of python's built-in types, like int and list, etc. I've run into some trouble, which I could explain with a couple simple...
5
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++: ...
4
by: dustin.getz | last post by:
consider the following working loop where Packet is a subclass of list, with Packet.insert(index, iterable) inserting each item in iterable into Packet at consecutive indexes starting at index. ...
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:
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
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
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...
0
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...
0
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...
0
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...

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.