Three types of traversal (ordinal and value) methods for the Python list

Source: Internet
Author: User
Tags python list
Three ways to iterate through the list of numbers and values:

Recently learn the language of Python, feel its work efficiency has a great improvement, special on Valentine's Day wrote this blog, the following nonsense say, direct sticker code

#!/usr/bin/env python#-*-coding:utf-8-*-if __name__ = = ' __main__ ':    list = [' html ', ' JS ', ' css ', ' python ']    # method 1    print ' traversal list Method 1: ' For    i in list:        print ("Ordinal:%s   value:%s"% (List.index (i) + 1, i))    print ' \ n Traverse list Method 2: ' 
 # Method 2 for    I in range (len list):        print ("Ordinal:%s   value:%s"% (i + 1, list[i])    # Method 3    print ' \ n Traverse list Method 3: '    for-I, Val in enumerate (list):        print ("Ordinal:%s   value:%s"% (i + 1, val))    # Method 3    print ' \ n Traverse list Method 3 (set traverse on Initial position, changed only the starting sequence number): ' For    I, Val in enumerate (list, 2):        print ("Ordinal:%s   value:%s"% (i + 1, val))

The results after running the code are as follows:

Introduce the enumerate () method here and look at the Help () function to see the following results:

Finally, the second parameter of the enumerate () function only changes the starting value of the ordinal, and does not change the other stuff.

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.