473,699 Members | 2,734 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Why can't you assign to a list in a loop without enumerate?

In the following code snippet, I attempt to assign 10 to every index in
the list a and fail because when I try to assign number to 10, number
is a deep copy of the ith index (is this statement correct?).
>>a = [1,2,3,4,5]
for number in a:
.... number = 10
....
>>a
[1, 2, 3, 4, 5]

So, I have to resort to using enumerate to assign to the list:
>>for i, number in enumerate(a):
.... a[i] = 10
....
>>a
[10, 10, 10, 10, 10]

My question is, what was the motivation for returning a deep copy of
the value at the ith index inside a for loop instead of the value
itself? Also, is there any way to assign to a list in a for loop (with
as little code as used above) without using enumerate?

Thanks,

Danny

Oct 31 '06 #1
12 2085
Danny Colligan wrote:
My question is, what was the motivation for returning a deep copy of
the value at the ith index inside a for loop instead of the value
itself?
I'm not sure the words "deep copy" and "value" really means what you
think they do. maybe you should spend a little time with Python's
documentation, instead of making up absurd theories about how things
might work, only to get disappointed every time reality disagrees.
Also, is there any way to assign to a list in a for loop (with
as little code as used above) without using enumerate?
what's wrong with using enumerate? or a list comprehension? or some
other of the many different ways you can use to build a list from a set
of values?

</F>

Oct 31 '06 #2
"Danny Colligan" <da***********@ gmail.comwrote:
In the following code snippet, I attempt to assign 10 to every index in
the list a and fail because when I try to assign number to 10, number
is a deep copy of the ith index (is this statement correct?).
No. There is no copying involved.

Before the assignment, number is a reference to the object to which the ith
element of the list also refers. After the assignment you have rebound the
variable 'number' so it refers to the value 10. You won't affect the list
that way.
My question is, what was the motivation for returning a deep copy of
the value at the ith index inside a for loop instead of the value
itself?
There is no copying going on. It returns the value itself, or at least a
reference to it.
Also, is there any way to assign to a list in a for loop (with
as little code as used above) without using enumerate?
a[:] = [10]*len(a)

or more usually something like:

a = [ fn(v) for v in a ]

for some suitable expression involving the value. N.B. This last form
leaves the original list unchanged: if you really need to mutate it in
place assign to a[:] as in the first example, but if you are changing all
elements in the list then you usually want a new list.

Oct 31 '06 #3
I'm not quite sure what your asking, but I'll give it a shot.

You do not have to use enumerate, you can use other methods just as
range(len(seque nce)), but the reason you cannot asign a value is
because a for loop iterates a sequence meaning when you do

for a in [1, 2, 3, 4, 5]:
...
a is just a value pulled from the sequence iteration.

just like i and number is a value pulled from the iteration in

for i, number in enumerate(a):
...

(That was worded badly :/ I apologise.)
Danny Colligan wrote:
In the following code snippet, I attempt to assign 10 to every index in
the list a and fail because when I try to assign number to 10, number
is a deep copy of the ith index (is this statement correct?).
>a = [1,2,3,4,5]
for number in a:
... number = 10
...
>a
[1, 2, 3, 4, 5]

So, I have to resort to using enumerate to assign to the list:
>for i, number in enumerate(a):
... a[i] = 10
...
>a
[10, 10, 10, 10, 10]

My question is, what was the motivation for returning a deep copy of
the value at the ith index inside a for loop instead of the value
itself? Also, is there any way to assign to a list in a for loop (with
as little code as used above) without using enumerate?

Thanks,

Danny
Oct 31 '06 #4
I see. Thanks for the helpful response.

Danny

Duncan Booth wrote:
"Danny Colligan" <da***********@ gmail.comwrote:
In the following code snippet, I attempt to assign 10 to every index in
the list a and fail because when I try to assign number to 10, number
is a deep copy of the ith index (is this statement correct?).

No. There is no copying involved.

Before the assignment, number is a reference to the object to which the ith
element of the list also refers. After the assignment you have rebound the
variable 'number' so it refers to the value 10. You won't affect the list
that way.
My question is, what was the motivation for returning a deep copy of
the value at the ith index inside a for loop instead of the value
itself?

There is no copying going on. It returns the value itself, or at least a
reference to it.
Also, is there any way to assign to a list in a for loop (with
as little code as used above) without using enumerate?

a[:] = [10]*len(a)

or more usually something like:

a = [ fn(v) for v in a ]

for some suitable expression involving the value. N.B. This last form
leaves the original list unchanged: if you really need to mutate it in
place assign to a[:] as in the first example, but if you are changing all
elements in the list then you usually want a new list.
Oct 31 '06 #5
Danny Colligan wrote:
In the following code snippet, I attempt to assign 10 to every index in
the list a and fail because when I try to assign number to 10, number
is a deep copy of the ith index (is this statement correct?).
It's quite easy to find out:

class Foo(object):
def __init__(self, num):
self.num = num
def __repr__(self):
return "foo %d at %d" % (self.num, id(self))

foos = [Foo(i) for i in range(10)]
print foos
=[foo 0 at 47281508865040, foo 1 at 47281508865104, foo 2 at
47281508865168, foo 3 at 47281508865232, foo 4 at 47281508865296, foo 5
at 47281508865360, foo 6 at 47281508865424, foo 7 at 47281508865488, foo
8 at 47281508865552, foo 9 at 47281508865616]

for foo in foos:
foo.num = foo.num * 2
print foos
=[foo 0 at 47281508865040, foo 2 at 47281508865104, foo 4 at
47281508865168, foo 6 at 47281508865232, foo 8 at 47281508865296, foo 10
at 47281508865360, foo 12 at 47281508865424, foo 14 at 47281508865488,
foo 16 at 47281508865552, foo 18 at 47281508865616]

Seems like your statement is *not* correct.
>>>a = [1,2,3,4,5]
for number in a:
... number = 10
Note that you are *not* "assign(ing ) 10 to every index in the list"
here. Rebinding the local name 'number' in each iteration only makes
this name refer to another object (implying of course loosing the
reference to the current list element). Then - on the following
iteration - the name 'number' is rebound to the next object in the list.
>>>a
[1, 2, 3, 4, 5]
>>for foo in foos:
.... original = foo
.... foo = Foo(10)
.... print "original : %s - foo : %s" % (original, foo)
....
original : foo 0 at 47281508865040 - foo : foo 10 at 47281508864144
original : foo 2 at 47281508865104 - foo : foo 10 at 47281508864144
original : foo 4 at 47281508865168 - foo : foo 10 at 47281508864144
original : foo 6 at 47281508865232 - foo : foo 10 at 47281508864144
original : foo 8 at 47281508865296 - foo : foo 10 at 47281508864144
original : foo 10 at 47281508865360 - foo : foo 10 at 47281508864144
original : foo 12 at 47281508865424 - foo : foo 10 at 47281508864144
original : foo 14 at 47281508865488 - foo : foo 10 at 47281508864144
original : foo 16 at 47281508865552 - foo : foo 10 at 47281508864144
original : foo 18 at 47281508865616 - foo : foo 10 at 47281508864144
So, I have to resort to using enumerate to assign to the list:
Yes. That's still far better than having to manually check for sequence
boundaries and track current index.
>>>for i, number in enumerate(a):
... a[i] = 10
...
>>>a
[10, 10, 10, 10, 10]
Just for the record: the notation 'a[x] = y' in fact calls
'a.__setitem__( x, y)'. It's really just calling a method that alters the
state of object a.
My question is, what was the motivation for returning a deep copy of
the value at the ith index inside a for loop instead of the value
itself?
Forget about values. Think objects.
>>i = 10
i.__class__
<type 'int'>
>>dir(i)
['__abs__', '__add__', '__and__', '__class__', '__cmp__', '__coerce__',
'__delattr__', '__div__', '__divmod__', '__doc__', '__float__',
'__floordiv__', '__getattribute __', '__getnewargs__ ', '__hash__',
'__hex__', '__init__', '__int__', '__invert__', '__long__',
'__lshift__', '__mod__', '__mul__', '__neg__', '__new__', '__nonzero__',
'__oct__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__',
'__rdiv__', '__rdivmod__', '__reduce__', '__reduce_ex__' , '__repr__',
'__rfloordiv__' , '__rlshift__', '__rmod__', '__rmul__', '__ror__',
'__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__',
'__rxor__', '__setattr__', '__str__', '__sub__', '__truediv__', '__xor__']
>>i.__abs__()
10

Also, is there any way to assign to a list in a for loop (with
as little code as used above) without using enumerate?
What's the problem with enumerate() ?

--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom. gro'.split('@')])"
Oct 31 '06 #6
In the following code snippet, I attempt to assign 10 to every index in
the list a and fail because when I try to assign number to 10, number
is a deep copy of the ith index (is this statement correct?).
Sorta...just like with function parameters, there are mutables
and immutables.
>>>a = [1,2,3,4,5]
for number in a:
... number = 10
...
>>>a
[1, 2, 3, 4, 5]
Just as with a function (currently discussed on another thread
recently), you have the following behavior:
>>def a(x):
.... x = 42
....
>>deb b(x):
.... x.append(42)
....
>>g = 1
h = [1]
a(g)
b(h)
g
1
>>h
[1, 42]
you have similar behavior:
>>a = [[1],[2],[3],[4],[5]]
for thing in a:
.... thing.append(10 )
....
>>a
[[1, 10], [2, 10], [3, 10], [4, 10], [5, 10]]

Lists/sets/etc are mutable. Strings, numbers,
So, I have to resort to using enumerate to assign to the list:
>>>for i, number in enumerate(a):
... a[i] = 10
...
>>>a
[10, 10, 10, 10, 10]
This would commonly be written with a list comprehension:

a = [10 for _ in a]

or

a = [10] * len(a)

or, if that was a general case of something more specific with
some "if" brains behind it, you can do things like

a = [odd(v) and 10 or v for v in a]

to only change them to 10 where the value is odd.
My question is, what was the motivation for returning a deep copy of
the value at the ith index inside a for loop instead of the value
itself? Also, is there any way to assign to a list in a for loop (with
as little code as used above) without using enumerate?

As stated above, it returns the item...if it's mutable, you can
mutate it. If it's an immutable (like your numbers), you just
change the variable in the local scope of the loop.
-tkc


Oct 31 '06 #7
Fredrik Lundh wrote:
what's wrong with using enumerate? or a list comprehension? or
some other of the many different ways you can use to build a list
from a set of values?
Shouldn't there be one -- and preferably only one -- obvious way to
do it? 8)

Python Cookbook says "enumerate( )", is this still correct with 2.5?

Regards,
Björn

--
BOFH excuse #195:

We only support a 28000 bps connection.

Nov 1 '06 #8
Bjoern Schliessmann wrote:
>what's wrong with using enumerate? or a list comprehension? or
some other of the many different ways you can use to build a list
from a set of values?

Shouldn't there be one -- and preferably only one -- obvious way to
do it? 8)

Python Cookbook says "enumerate( )", is this still correct with 2.5?
define "it".

</F>

Nov 1 '06 #9
Bjoern Schliessmann wrote:
Fredrik Lundh wrote:
>what's wrong with using enumerate? or a list comprehension? or
some other of the many different ways you can use to build a list
from a set of values?

Shouldn't there be one -- and preferably only one -- obvious way to
do it? 8)
The obvious one is to use enumerate.
TOOWTDI allows less obvious ways to exist.

--
Roberto Bonvallet
Nov 1 '06 #10

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

Similar topics

5
2129
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, assuming that I have a list like: mylist = I would like to find the indices of the elements in the list that are equal to 1 (in this case, the 1,2,3,4,9 elements are equal to 1). I could easily
3
2829
by: fdsl ysnh | last post by:
--- python-list-request@python.orgдµÀ: > Send Python-list mailing list submissions to > python-list@python.org > > To subscribe or unsubscribe via the World Wide Web, > visit > http://mail.python.org/mailman/listinfo/python-list > or, via email, send a message with subject or body > 'help' to
32
2781
by: Robin Becker | last post by:
Is there some smart/fast way to flatten a level one list using the latest iterator/generator idioms. The problem arises in coneverting lists of (x,y) coordinates into a single list of coordinates eg f() --> or g(,) -->
23
7312
by: Brian Blais | last post by:
Hello, I have two lists, one with strings (filenames, actually), and one with a real-number rank, like: A= B= I'd like to sort list A using the values from B, so the result would be in this example,
9
17401
by: William Meyer | last post by:
hi, I need to get the index of an object in a list. I know that no two objects in the list are the same, but objects might evaluate as equal. for example list = for object in list: objectIndex = list.index(object) print objectIndex
22
1703
by: joh12005 | last post by:
hello, i'm looking for a way to have a list of number grouped by consecutive interval, after a search, for example : => , , , ]
5
2871
by: Greg Corradini | last post by:
Hello All, I'm attempting to create multiple dictionaries at once, each with unique variable names. The number of dictionaries i need to create depends on the length of a list, which was returned from a previous function. The pseudo code for this problem would be: returnedlist = count = 0 for i in returnedlist: if count < len(returnedlist):
4
1478
by: eight02645999 | last post by:
hi i have a list (after reading from a file), say data = I wanted to insert a word after every 'a', and before every 'd'. so i use enumerate this list: for num,item in enumerate(data): if "a" in item: data.insert(num+1,"aword") if "d" in item:
2
6588
by: cloftis | last post by:
Using VS2003, VB and MSHTML, Using an HTMLSpanElement I want to enumerate the attributes of a SPAN tag. 1 'For testing sake 2 Dim strMarkup as String = "<span attr1='somevalue' attr2='somevalue' attrN='...'>markup</span>" 3 Dim objSpan As HTMLSpanElement = browser.Document.createElement("span") 4 objSpan.innerHTML = strMarkup
0
8685
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9171
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, 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...
0
9032
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 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...
1
8905
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,...
0
8880
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 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...
0
7743
agi2029
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...
1
3053
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 we have to send another system
2
2342
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2008
bsmnconsultancy
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...

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.