weird iteration/assignment problem

C

cirfu

for i in xrange(0, len(texts)):
texts = "yes"

for i in texts:
i = "no"

why is the first one working but not the second. i mean i see why the
firts one works but i dont udnerstand why the second doesnt.
 
D

Diez B. Roggisch

cirfu said:
for i in xrange(0, len(texts)):
texts = "yes"

for i in texts:
i = "no"

why is the first one working but not the second. i mean i see why the
firts one works but i dont udnerstand why the second doesnt.


Because in the second you only bind the contents of texts to a name i.

But that doesn't mean that i magically became an "alias" for
texts[index] - it just happens to point at the same object.

To accomplish what you want, the pythonic idiom is to use enumerate:

for i, text in enumerate(texts):
text = "yes"

Diez
 
M

Matimus

cirfu said:
for i in xrange(0, len(texts)):
texts = "yes"

for i in texts:
i = "no"
why is the first one working but not the second. i mean i see why the
firts one works but i dont udnerstand why the second doesnt.

Because in the second you only bind the contents of texts to a name i.

But that doesn't mean that i magically became an "alias" for
texts[index] - it just happens to point at the same object.

To accomplish what you want, the pythonic idiom is to use enumerate:

for i, text in enumerate(texts):
text = "yes"

Diez


That should be:

for i, text in enumerate(texts):
texts = "yes"
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,009
Latest member
GidgetGamb

Latest Threads

Top