Enumerate () function usage in Python

Source: Internet
Author: User

Enumerate () function usage in Python

First out a topic: 1. There is a list= [1, 2, 3, 4, 5, 6]
Please print the output:
0, 1
1, 2
2, 3
3, 4
4, 5
5, 6
Print output,
2. Reverse list to [6, 5, 4, 3, 2, 1]
3. Select the even number in a and the result is [4, 8, 12]

This example uses the use of enumerate in Python. By the way, enumerate the usage of the count in the For loop, the enumerate argument is a variable that can be traversed, such as a string, a list, etc.; the return value is the enumerate class.

The sample code looks like this:

Problem 1.2.3. Work together, the code is as follows:

list=[1,2,3,4,5,6]

For I, J in Enumerate (list)

Print (I,J)

LIST2=LIST[::-1]

List3=[i*2 for I in the list if not i%2]//i%2==0 proof i is even, not 0 is true, that is, I is an even number when i*2

Print (LIST2,LIST3)

>>>0,1

>>>1,2

>>>2,3

>>>3,4

>>>4,5

>>>5,6

>>>[6,5,4,3,2,1]

>>>[4,8,12]

You can use enumerate when both the index and value values are required. The following separate strings, arrays, lists, and dictionaries through the elements in the sequence and their subscripts:

One, String:

For i,j in enumerate (' ABCDE '):

Print I,j

>>>0,a

>>>1,b

>>>2,c

>>>3,d

>>>4,e

Two, array:

For i,j in enumerate ((' a ',' B ',' C ')):

  Print I,j

The output is:

>>>0 A

>>>1,b

>>>2,c

Three, List:

The case has been said at the beginning.

Four, Dictionary:

For I,j in enumerate ({' a ':1,' B ':2}):

  Print I,j

The output is:

>>>0 A

>>>1,b

Enumerate () function usage in Python

Related Article

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.