What does enumerate() mean?

后端 未结 5 596
别跟我提以往
别跟我提以往 2020-11-22 01:24

What does for row_number, row in enumerate(cursor): do in Python?

What does enumerate mean in this context?

5条回答
  •  温柔的废话
    2020-11-22 02:02

    I am reading a book (Effective Python) by Brett Slatkin and he shows another way to iterate over a list and also know the index of the current item in the list but he suggests that it is better not to use it and to use enumerate instead. I know you asked what enumerate means, but when I understood the following, I also understood how enumerate makes iterating over a list while knowing the index of the current item easier (and more readable).

    list_of_letters = ['a', 'b', 'c']
    for i in range(len(list_of_letters)):
        letter = list_of_letters[i]
        print (i, letter)
    

    The output is:

    0 a
    1 b
    2 c
    

    I also used to do something, even sillier before I read about the enumerate function.

    i = 0
    for n in list_of_letters:
        print (i, n)
        i += 1
    

    It produces the same output.

    But with enumerate I just have to write:

    list_of_letters = ['a', 'b', 'c']
    for i, letter in enumerate(list_of_letters):
        print (i, letter)
    

提交回复
热议问题