Python data type - list

the list

A list (list) is an ordered and changeable collection, and duplicate members are allowed in the list.

create list

create empty list

In Python, []represents an empty list. for example:

a = []
print(type(a))  # <class 'list'>
print(a)        # []

In addition, list()an empty list can also be created by means of . for example:

a = list()
print(type(a))  # <class 'list'>
print(a)        # []

create non-empty list

The initial value of the list can be set in the list when it is created []. for example:

a = [1, 2, 3, 4, 5]
print(type(a))  # <class 'list'>
print(a)        # [1, 2, 3, 4, 5]

It should be noted that the elements stored in the list can be of different types. for example:

a = [1, 'hello', True, [4, 5, 6]]
print(type(a))  # <class 'list'>
print(a)        # [1, 'hello', True, [4, 5, 6]]

Add list element

append method

Use the append method to add an element to the end of the list. for example:

a = [1, 2, 3, 4]
a.append(2021)
a.append('dragon')
print(a)  # [1, 2, 3, 4, 2021, 'dragon']

insert method

Use the insert method to add an element at the specified subscript position. for example:

a = [1, 2, 3, 4]
a.insert(1, 5)
a.insert(100, 'dragon')
print(a)  # [1, 5, 2, 3, 4, 'dragon']

Explain:

  • Python is an object-oriented language, so the created list is essentially an object, and append and insert here are member methods of the list.
  • When calling the insert method, if the specified index exceeds the maximum subscript in the list, the element to be inserted is inserted at the end of the list.

delete list element

pop method

Use the pop method to delete the last element of the list. for example:

a = [1, 2, 3, 4]
a.pop()
print(a)  # [1, 2, 3]

The element at the specified subscript position can also be deleted using the pop method. for example:

a = [1, 2, 3, 4]
a.pop(1)
print(a)  # [1, 3, 4]

remove method

Use the remove method to specify to delete elements of a specific value in the list. for example:

a = [1, 2, 3, 4]
a.remove(1)
print(a)  # [2, 3, 4]

If more than one element of a particular value exists in the list, the remove method removes only the first occurrence. for example:

a = [1, 2, 3, 4, 1]
a.remove(1)
print(a)  # [2, 3, 4, 1]

Find list element

in and in not operators

Use the in and in not operators to determine whether an element exists in the list. for example:

a = [1, 2, 3, 4]
print(1 in a)       # True
print(10 in a)      # False
print(1 not in a)   # False
print(10 not in a)  # True

index method

You can also use the index method to determine whether an element exists in the list. for example:

a = [1, 2, 3, 4]
print(a.index(3))  # 2
# print(a.index(10)) # 不存在,抛异常

Note: When using the index method, if the element to be found is in the list, the subscript of the element will be returned, otherwise an exception will be thrown.

subscript access list element

access list element

[]The element at the specified subscript position can be obtained through the subscript access operator . for example:

a = [1, 2, 3, 4]
print(a[2])  # 3

In addition, the value of the accessed element can also be modified through the subscript. for example:

a = [1, 2, 3, 4]
a[2] = 100
print(a)  # [1, 2, 100, 4]

Note: If the value of the specified subscript exceeds the maximum subscript in the list, an exception will be thrown.

negative index

The subscripts we usually say start counting from 0, and the subscripts here can take negative numbers. We call them negative indexes. Negative indexes actually start from the last element of the list and go forward, in order -1, -2, -3, .... For example:
insert image description here
So if you want to access the last element of the list, you can directly access the element with the subscript -1. for example:

a = [1, 2, 3, 4]
print(a[-1])  # 4

iterate over list elements

for loop traversal

The for loop in Python can directly traverse an iterable object. for example:

a = [1, 2, 3, 4]
for elem in a:
    print(elem)

But it should be noted that the modification of the loop variable under this method will not affect the element values ​​in the list. for example:

a = [1, 2, 3, 4]
for elem in a:
    print(elem)
    elem = elem + 10  # 不会影响列表中的元素值
print(a)  # [1, 2, 3, 4]

In addition, you can also use the for loop to traverse the subscripts of the list elements, and then traverse the elements in the list sequentially in the form of subscripts. for example:

a = [1, 2, 3, 4]
for i in range(len(a)):
    print(a[i])

By traversing the list elements in this way, it is possible to modify the list elements. for example:

a = [1, 2, 3, 4]
for i in range(len(a)):
    print(a[i])
    a[i] = a[i] + 10  # 会影响列表中的元素值
print(a)  # [11, 12, 13, 14]

To explain: the number of elements in the list can be obtained through the len function.

while loop traverses

You can also use the while loop to subscript the elements of the traversal list, and then traverse the elements in the list in turn by subscripting. for example:

a = [1, 2, 3, 4]
i = 0
while i < len(a):
    print(a[i])
    i += 1

sublist extraction

[start subscript: end subscript]

[起始下标 : 结束下标]A set of elements can be extracted from the list, starting from the start subscript to the end subscript . for example:

a = [1, 2, 3, 4]
print(a[1:3])  # [2, 3]

Note: The extracted sublist contains the elements of the start subscript, but does not contain the elements of the end subscript (close before and open after).

Omit bounds when slicing

The process of extracting sublists is also called the process of slicing, and the [起始下标 : 结束下标]start subscript or end subscript can be omitted when slicing in the way.

  • If [起始下标 : ]sliced ​​in , the elements in the sublist include the element at the start subscript and its successors.
  • If [ : 结束下标]sliced ​​in , the elements in the sublist include all elements up to the closing subscript.
  • If [ : ]sliced ​​in a way, the elements in the sublist include all elements in the original list.

Slice example:

a = [1, 2, 3, 4]
print(a[1:])   # [2, 3, 4]
print(a[:2])   # [1, 2]
print(a[:-1])  # [1, 2, 3]
print(a[:])    # [1, 2, 3, 4]

Note: Negative indices can also be used when slicing.

Specify the step size when slicing

Slicing in [起始下标 : 结束下标 : 步长]the way can specify the step size, that is, how many steps the subscript increments after each element is accessed. for example:

a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
print(a[::1])     # [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
print(a[::2])     # [1, 3, 5, 7, 9]
print(a[::3])     # [1, 4, 7, 0]
print(a[1:-1:2])  # [2, 4, 6, 8]

In addition, the step size specified when slicing can also be a negative number, which means that elements are extracted from the back to the front. for example:

a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
print(a[::-1])  # [0, 9, 8, 7, 6, 5, 4, 3, 2, 1]
print(a[::-2])  # [0, 8, 6, 4, 2]

Subscript out of bounds problem when slicing

If the subscript filled in when slicing exceeds the valid range, no exception will be thrown after running the program, but elements that meet the requirements will be extracted as much as possible. for example:

a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
print(a[1:100])  # [2, 3, 4, 5, 6, 7, 8, 9, 0]

spliced ​​list

Use + to splice lists

Use + to concatenate two lists together. for example:

a = [1, 2, 3]
b = [4, 5, 6]
c = a + b
print(a)  # [1, 2, 3]
print(b)  # [4, 5, 6]
print(c)  # [1, 2, 3, 4, 5, 6]

Note: After using + splicing, a new list will be generated, and this operation will not affect the two original lists.

extend method

Using the extend method, one list can be concatenated to the back of another list. for example:

a = [1, 2, 3]
b = [4, 5, 6]
a.extend(b)
print(a)  # [1, 2, 3, 4, 5, 6]
print(b)  # [4, 5, 6]

Note: a.extend(b) The elements in the b list are spliced ​​to the back of the a list, and this operation will not modify the b list.

Use += to concatenate lists

You can also concatenate one list after another using +=. for example:

a = [1, 2, 3]
b = [4, 5, 6]
a += b
print(a)  # [1, 2, 3, 4, 5, 6]
print(b)  # [4, 5, 6]

Explain:

  • Both the += and extend methods can concatenate one list to the other, but using the extend method is more efficient.
  • Because a += bit is equivalent to a = a + b, in the splicing process, the spliced ​​list will be constructed first, and then the original list of a will be released, and then the spliced ​​list will be assigned to a.
  • Instead,a.extend(b) the elements in the b list are directly spliced ​​to the back of the a list, avoiding unnecessary release operations.

List common interface summary

List operations:

list manipulation Way
sublist extraction thislist[start:end:step](Front closed and rear open)
list check inandin not
list concatenation +and+=
list length len()function

List member functions:

member function Function
copy copy list
clear clear the list
append Add an element to the end of the list
insert Add an element at the specified subscript position in the list
extend Adds list elements (or any iterable) to the end of the current list
pop Delete the element at the specified subscript position (the default is the last one)
remove removes the element with the specified value (first occurrence)
index Returns the subscript (first occurrence) of the element with the specified value
count Returns the number of elements with the specified value
reverse Reverse the order of elements in a list
sort Sort the elements in the list

Guess you like

Origin blog.csdn.net/chenlong_cxy/article/details/127615928
Recommended