A detailed description of the usage of the enumerate function in Python

Source: Internet
Author: User
This article describes how to use the enumerate function in Python. the enumerate function is used to traverse elements in a sequence and their subscript. it is mostly used to get counts in a for loop. the enumerate parameter is a variable that can be traversed, such as string and list

In general, if you want to traverse both the index and element of a list or array, write as follows:

for i in range (0,len(list)):   print i ,list[i]

However, this method is somewhat cumbersome. it is more straightforward and elegant to use the built-in enumerrate function. let's take a look at the definition of enumerate:

def enumerate(collection):   'Generates an indexed series: (0,coll[0]), (1,coll[1]) ...'      i = 0    it = iter(collection)    while 1:    yield (i, it.next())    i += 1


Enumerate combines an array or list into an index sequence. This makes it easier to obtain the index and index content as follows:

for index,text in enumerate(list):   print index ,text


Code Example 1:

i = 0seq = ['one', 'two', 'three']for element in seq:    print i, seq[i]    i += 1

0 one

1 two

2 three


Code Example 2:

seq = ['one', 'two', 'three']for i, element in enumerate(seq):    print i, seq[i]

0 one

1 two

2 three


Code Example 3:

for i,j in enumerate('abc'):    print i,j

0

1 B

2 c

The above is a detailed description of the enumerate function usage in Python. For more information, see other related articles in the first PHP community!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.