Enumerate object is destroyed by casting?

Discussion in 'Python' started by Nick Jacobson, Aug 25, 2004.

  1. Casting an 'enumerate' object destroys it?? Is that supposed to
    happen, or is it a bug?


    For example:
    a = ['a', 'b', 'c']
    e = enumerate(a)
    print dict(e)
    print dict(e)


    Result:
    {0: 'a', 1: 'b', 2: 'c'}
    {}
    Nick Jacobson, Aug 25, 2004
    #1
    1. Advertising

  2. Nick Jacobson wrote:

    > Casting an 'enumerate' object destroys it??  Is that supposed to
    > happen, or is it a bug?
    >
    >
    > For example:
    > a = ['a', 'b', 'c']
    > e = enumerate(a)
    > print dict(e)
    > print dict(e)
    >
    >
    > Result:
    > {0: 'a', 1: 'b', 2: 'c'}
    > {}


    This is supposed to happen. Enumerate objects are essentially generators --
    casting the object doesn't "destroy" it; but iterating over its values
    "uses them up". In other words, after the first dict() call, your
    enumerator is now empty. The same thing would happen if you simply iterated
    over the object, like:

    for thing in e:
    print thing
    Jeffrey Froman, Aug 25, 2004
    #2
    1. Advertising

  3. Nick Jacobson wrote:
    > Casting an 'enumerate' object destroys it?? Is that supposed to
    > happen, or is it a bug?
    >
    >
    > For example:
    > a = ['a', 'b', 'c']
    > e = enumerate(a)
    > print dict(e)
    > print dict(e)
    >
    >
    > Result:
    > {0: 'a', 1: 'b', 2: 'c'}
    > {}


    This is not casting (there is no casting in Python). It is creating a
    new dict from an iterable. enumerate(a) creates an iterable that runs
    over the items *once*. After that there is nothing left to return.

    HTH,

    Shalabh
    Shalabh Chaturvedi, Aug 25, 2004
    #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. enrique
    Replies:
    8
    Views:
    538
    Kevin McMurtrie
    Apr 29, 2005
  2. Charles Herman

    when is object destroyed?

    Charles Herman, Nov 6, 2003, in forum: C++
    Replies:
    2
    Views:
    423
    lilburne
    Nov 6, 2003
  3. Anon Email

    Is this object destroyed?

    Anon Email, Dec 7, 2003, in forum: C++
    Replies:
    2
    Views:
    307
    Anon Email
    Dec 8, 2003
  4. Ioannis Vranos
    Replies:
    9
    Views:
    305
    Ioannis Vranos
    May 16, 2005
  5. Raga
    Replies:
    0
    Views:
    286
Loading...

Share This Page