Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Python > weird iteration/assignment problem

Reply
Thread Tools

weird iteration/assignment problem

 
 
cirfu
Guest
Posts: n/a
 
      06-13-2008
for i in xrange(0, len(texts)):
texts[i] = "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.
 
Reply With Quote
 
 
 
 
Diez B. Roggisch
Guest
Posts: n/a
 
      06-13-2008
cirfu schrieb:
> for i in xrange(0, len(texts)):
> texts[i] = "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[i] = "yes"

Diez
 
Reply With Quote
 
 
 
 
Matimus
Guest
Posts: n/a
 
      06-13-2008
On Jun 13, 8:07 am, "Diez B. Roggisch" <(E-Mail Removed)> wrote:
> cirfu schrieb:
>
> > for i in xrange(0, len(texts)):
> > texts[i] = "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[i] = "yes"
>
> Diez


That should be:

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


 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Re: A Weird Appearance for a Weird Site Beauregard T. Shagnasty HTML 1 01-21-2011 04:17 PM
Re: A Weird Appearance for a Weird Site richard HTML 0 01-21-2011 07:10 AM
Re: A Weird Appearance for a Weird Site dorayme HTML 1 01-21-2011 06:51 AM
Re: A Weird Appearance for a Weird Site richard HTML 0 01-21-2011 06:46 AM
newbie with a weird technical problem (@ least I think it's weird) will Ruby 6 12-27-2006 04:46 PM



Advertisments