473,473 Members | 2,248 Online
Bytes | Software Development & Data Engineering Community
Create 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 2068
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(sequence)), 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
Fredrik Lundh wrote:
define "it".
Sorry! I mean iterating over a list and having the list index
available in the loop. Like:

for i, thing in enumerate(things):
pass

Regards,
Björn

--
BOFH excuse #254:

Interference from lunar radiation

Nov 1 '06 #11
Bjoern Schliessmann wrote:
>define "it".

Sorry! I mean iterating over a list and having the list index
available in the loop. Like:

for i, thing in enumerate(things):
pass
"enumerate" is the obviously right thing for this, sure. but it's not
necessarily the right thing for the OP's "I want to create a new list
based on an existing list". modifying the existing list is usually not
the most efficient way to do that.

</F>

Nov 1 '06 #12
Fredrik Lundh wrote:
"enumerate" is the obviously right thing for this, sure.
K.
but it's not necessarily the right thing for the OP's "I want to
create a new list based on an existing list". modifying the
existing list is usually not the most efficient way to do that.
Agreed.

Regards,
Björn

--
BOFH excuse #418:

Sysadmins busy fighting SPAM.

Nov 1 '06 #13

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

Similar topics

5
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,...
3
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 >...
32
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...
23
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...
9
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:...
22
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
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...
4
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...
2
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'...
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...
1
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
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,...
0
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
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 ...

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.