What does enumerate mean ?

What does enumerate mean ?

Asked on November 19, 2018 in tkinter.
Add Comment


  • 3 Answer(s)

    Here is the solution is

                  The enumerate() function adds a counter to an iterable. So for each element in cursor, a tuple is produced with (counter, element); the for loop binds that   to row_number and row, respectively.

     Here is the code is

    >>> elements = ('foo', 'bar', 'baz')
    >>> for elem in elements:
    ...     print elem
    ... 
    foo
    bar
    baz
    >>> for count, elem in enumerate(elements):
    ...     print count, elem
    ... 
    0 foo
    1 bar
    2 baz
    

            The  enumerate() starts counting at 0 but a second integer argument, it’ll start from that number instead.

    >>> for count, elem in enumerate(elements, 42):
    ...     print count, elem
    ... 
    42 foo
    43 bar
    44 baz
    

              The to re-implement enumerate() in Python, there are two ways of achieving that;
    one using  itertools.count() to do the counting, the other manually counting in a generator function

     

    from itertools import count
    def enumerate(it, start=0):
    # return an iterator that adds a counter to each element of it
    return zip(count(start), it)
     
    def enumerate(it, start=0):
    count = start
      for elem in it:
              yield (count, elem)
              count += 1
    

    The actual implementation in C is closer to the latter, with optimisations to reuse a single tuple object for the common fori….,

     

    Answered on November 19, 2018.
    Add Comment

    The tkinter in Python and came across the following code:

    for row_number, row in enumerate(cursor):
    

    The wondering what enumerate means in this context.

    Answered on November 19, 2018.
    Add Comment
    Here is  the solution is:
        The builtin generator function, see http://docs.python.org/2/library/functions.html#enumerate . In short, it yields the elements of an iterator, as well as an index number:
     
    Try this code
    for item in enumerate(["a", "b", "c"]):
        print item
    
     
    print
     
    (0, "a")
    (1, "b")
    (2, "c")
    
     
    This is  helpful if you want to loop over an interator, and also want to have an index counter available. If you want the counter to start from some other value (usually 1), you can give that as second argument to enumerate.
    Answered on November 19, 2018.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.