Python Basics-Lists (list)

Source: Internet
Author: User

1. List definition

list=[‘张三‘,‘李四‘,123]

2. Accessing the values in the list

print(list[0])>>:张三print(list[0:2])>>:[‘张三‘,‘李四‘]

3. Add element Append (), insert ()
3.1 Append () Append Data

list.append(231)

3.2 Insert () to add at the specified location

list.insert(1,‘马六‘)print(list)>>:[‘张三‘, ‘马六‘, ‘李四‘, 123]

4. Delete element Del,remove (), Pop ()
4.1 del

del list[0]print(list[0])>>:李四

4.2 Remove () by value

list.remove(123)print(list)>>:[‘张三‘, ‘李四‘, 231]

4.3 pop () is deleted according to the list subscript

list.pop(1)print(list)>>:[‘张三‘, 123, 231]

5.len () method, returns the list length

print(len(list))>>:4

6.sorted () method, for array sorting

list=[‘d‘,‘a‘,‘g‘,‘e‘]print(sorted(list))>>:[‘a‘, ‘d‘, ‘e‘, ‘g‘]

7.count () method to calculate the number of occurrences of an item of data in a list

list=[‘d‘,‘a‘,‘g‘,‘e‘,‘d‘]print(list.count(‘d‘))>>:2

8.extend () append another list to the end of the original list

list=[‘d‘,‘a‘,‘g‘,‘e‘,‘d‘]list1=[‘n‘,‘h‘]list.extend(list1)print(list)>>:[‘d‘, ‘a‘, ‘g‘, ‘e‘, ‘d‘, ‘n‘, ‘h‘]

9.index () The position in the list where the return value is located

list=[‘d‘,‘a‘,‘g‘,‘e‘,‘d‘]print(list.index(‘a‘))>>:1#如果有多个相同的值则返回第一个值的位置list=[‘d‘,‘a‘,‘g‘,‘e‘,‘d‘]print(list.index(‘d‘))>>:0

10.reverse () Inverse array

list=[‘d‘,‘a‘,‘g‘,‘e‘,‘d‘]list.reverse()print(list)>>:[‘d‘, ‘e‘, ‘g‘, ‘a‘, ‘d‘]

Python Basics-Lists (list)

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.