weird iteration/assignment problem

Discussion in 'Python' started by cirfu, Jun 13, 2008.

  1. cirfu

    cirfu Guest

    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.
     
    cirfu, Jun 13, 2008
    #1
    1. Advertising

  2. cirfu schrieb:
    > 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
     
    Diez B. Roggisch, Jun 13, 2008
    #2
    1. Advertising

  3. cirfu

    Matimus Guest

    On Jun 13, 8:07 am, "Diez B. Roggisch" <> wrote:
    > cirfu schrieb:
    >
    > > 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"
     
    Matimus, Jun 13, 2008
    #3
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. nagy
    Replies:
    36
    Views:
    1,024
    Terry Reedy
    Jul 20, 2006
  2. Chris
    Replies:
    34
    Views:
    1,552
  3. Rudi
    Replies:
    5
    Views:
    5,129
  4. will
    Replies:
    6
    Views:
    425
    Phrogz
    Dec 27, 2006
  5. ridcully
    Replies:
    2
    Views:
    102
    ridcully
    Nov 17, 2007
Loading...

Share This Page