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******@ozemai l.com.au http://members.ozemail.com.au/~pballard/ 6 5061
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
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
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******@ozema il.com.au> wrote in message
news:9d******** *************** **@posting.goog le.com... 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******@ozemai l.com.au http://members.ozemail.com.au/~pballard/
"Peter Ballard" <pb******@ozema il.com.au> wrote in message
news:9d******** *************** **@posting.goog le.com... 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
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
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 This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
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 interchangeable in all
circumstances (as long as they're paired) so there's no overloading to
muddy the language. Of course there could be some interesting problems
with current code that doesn't make a distinction, but it would be dead
easy to fix...
|
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* just
created a new pointer to the original value....
For example I wanted to initialize a list of empty lists....
a=, , , , ]
I thought there has to be a *really* easy way of doing it - after a
|
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, but try to use
an iterator of a list that you're mutating and watch it all fall to
pieces. That is, if you change the length of a section of the list
through which the iterator has already passed, it will lose track of
where it is. I think...
|
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 deletion_list:
del x
|
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?
http://david.tribble.com/text/cdiffs.htm#C99-cpp-keyword
http://www.inf.uni-konstanz.de/~kuehl/c++-faq/const-correctness.html#faq-18.13
Regards,
Markus
| |
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 examples. Lets say
I want an int-derived class that is initilized to one greater than what
it's constructor is given:
class myint(int):
def __new__(cls, intIn):
|
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)
|
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.
i=0
while(i<len(packet)-4):
if packet==Packet("01110"):
packet.insert(i, "01111")
i+=10 #skip the 5 bits inserted, and skip the 5 bits just
checked bc overlap should not trigger insertion
|
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:
|
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it.
First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
|
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...
| |
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...
|
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
|
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...
|
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...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |
by: bsmnconsultancy |
last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...
| |