List data types and common operations of python, and list data types of python

Source: Internet
Author: User

List data types and common operations of python, and list data types of python

A list is the most common Python data type. It can appear as a comma-separated value in square brackets.

Each element in the list is assigned a number-its location, or index. The first index is 0, the second index is 1, and so on.

Operations that can be performed on the list include indexing, slicing, adding, multiplication, and checking members. In addition, Python has built-in methods to determine the sequence length and the maximum and minimum elements.

You do not need to create a list of data items of the same type. You only need to enclose different data items separated by commas (,) in square brackets.

As follows:

list1 = ['physics', 'H2O', 1997, 2000]list2 = [1, 2, 3, 4, 5 ]list3 = ["a", "b", "c", "d"]

List slicing:

L [0: 2] Fetch the first to second elements of the list
L [] Fetch the third to fourth elements of the list
L [: 2] Fetch list elements 1, 3, 5 ....

Common Operations of the list are as follows:

Li = ['day', 'Eric ', 'rain']

Calculate the list length and Output

print(len(li))3 

Append the element "seven" to the list"

li.append("seven")

Insert the element "Tony" at the first position in the list"

li.insert(0, "tony")

Modify the element of the 2nd position in the list to "Kelly"

li[1] = "kelly"

Delete the "eric" element from the list"

li.remove("eric")

Delete the 2nd elements in the list

li.pop(1)

Delete 2nd to 4 elements from the list

for i in range(3):     li.pop(1)

Invert all elements in the list

# Method 1li [:-1] # method 2 list (reversed (li ))

Use enumrate to output the list element and serial number (sequence number starts from 100) for the index of the output list using for, len, and range)

for k, v in enumerate(li, 100):     print(k, v)

Use the for loop to output all elements in the list

for i in range(len(li)):     print(i)

 

 

 

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.