python learning 9 (list operation)

List operation

index() function: get the index of the specified element
Syntax:
list name.index(object)

print(a.index('l'))
  • When the list contains the same element, only the subscript index of the first element is displayed
  • The query element does not exist, and a valueerror error is thrown
  • Can be used in the specified star and stop (not including stop)
print(a.index('l',0,2))

List【】: Get the specified single element

  • Forward index: citation list name [number]
  • Negative index: citation list name [-number]

Slice: Get multiple specified elements. It
is a copy of the original list and a new list.
Syntax: list name [start, stop, step]

Determine whether the element exists.
Exist: element in list
does not exist: element not in list

Element traversal
for custom variable in list

Add list element

  1. append() adds an element after the list. Same list
  2. extend() adds at least one element after the list. Equivalent splicing
  3. insert() adds an element at the specified position in the list. Same list
  4. Slice = new list. Add multiple elements at the specified position in the list. Equivalent replacement

Delete list element

  1. remove() deletes one at a time, duplicate elements only delete the first one
  2. pop() deletes the element at the specified position, and deletes the last element if it is not specified
  3. Slice delete at least one
  4. clear() clear the list
  5. del() delete the list

Modify list elements

  1. Index assignment (one)
  2. Slice assignment (multiple)

Sort list elements

  1. sort() sort the original list
  2. sorted() generates a new list.
    Default reserve=false, ascending order
    reserve=true, descending order
    code example
lst=[1,2,3,7,5,6,4]
print(list(lst),id(lst))
#升序
lst.sort()
print(list(lst),id(lst))
#降序
lst.sort(reverse=True)
print(list(lst),id(lst))
#id相同证明是同一个列表

Result display
Insert picture description here
list production formula
List name=[expression for element in list]
code example

lst=[i*i*i for i in range(5)]
#0-4取数,求立方,放到lst中
print(list(lst))

Result display
Insert picture description here

Guess you like

Origin blog.csdn.net/qq_40551957/article/details/114238988