Python learning notes_ list

Posted by juancuca on Thu, 20 Jan 2022 21:34:27 +0100

Lists are equivalent to arrays in other languages
Multiple different data types can be stored in the list
How to create a list:
① Use brackets []
② Call the built-in function list()

lst = ['hello', 'world', 98]
lst2 = list(['hello', 'world', 98])
print(lst)
print(lst2)
print(lst[1])  # world
print(lst[-2])  # world

Features of the list:
① The list elements are arranged in order
The index starts from 0 from left to right and - 1 from right to left
② Index map unique data
③ Lists can store duplicate data
④ Mixed storage of any data type
⑤ Dynamically allocate and reclaim memory as needed

Query operation of list
1. Gets the index of the specified element in the list
Function: index()
If there are multiple identical elements in the checked list, only the index of the first element in the same element is returned
If the queried element does not exist in the list, a ValueError is thrown
You can find between the specified start and stop
2. Gets a single element in the list
Forward index from 0 to N-1; Reverse index from - N to - 1; The specified index does not exist. An indexError is thrown

lst = ['hello', 'world', 98, 'hello']
print(lst.index('hello'))  # 0
# print(lst.index('hey'))  # ValueError
print(lst.index('hello', 1, 3))  # ValueError because the indexes of 'hello' are 0 and 4, no 'hello' can be found in 1 to 2‘
lst = ['hello', 'world', 98, 'hello', 'world', 234]
print(lst[2])  # 98
print(lst[-3])  # hello
print(lst[10])  # IndexError: list index out of range

3. Gets multiple elements in the list
Slicing operation
Syntax format list name [start: Stop: step]
Result of slice: copy of original list fragment
Slice range: [start,stop), open left and close right, excluding stop
step defaults to 1 and is abbreviated as [start: stop]

# step is a positive number, and the slice is calculated from start to back:
# ① [: Stop: step], the first element of the slice is the first element of the list by default
# ② [start:: step], the last element of the slice is the last element of the list by default
# step is a complex number, and the slice is calculated from start to forward
# ① [: Stop: step], the first element of the slice is the last element of the list by default
# ② [start:: step], the last element of the slice is the first element of the list by default
lst = [10, 20, 30, 40, 50, 60, 70, 80]
print('Original list id: ', id(lst))
lst2 = lst[1:6:1]
print('Cut fragment id: ', id(lst2))  # id(lst2) != id(lst), that is, the cut-out fragment is a new list

4. Determines whether the specified element exists in the list
in,not in

lst = [10, 20, 'python', 'hello']
print(10 in lst)  # True
print(100 in lst)  # False
print(10 not in lst)  # False
print(100 not in lst)  # True

5. Traversal of elements in the list

lst = [10, 20, 'python', 'hello']
for item in lst:
    print(item)

6. Adding, deleting and modifying list elements

Adding list elements:
append() adds an action to the end of the list

# Add an element at the end of the list
lst = [10, 20, 30]
print('List before adding element and its id: ', lst, id(lst))
lst.append(100)
print('List after adding element and its id: ', lst, id(lst))
# As can be seen from the output, the id of the list will not change after adding the element

extend() adds at least one element to the end of the list

# Add an element at the end of the list
lst = [10, 20, 30]
print(lst)
lst2 = ['hello', 'world']
# lst.append(lst2)  # Add lst2 as an element to the end of the list
# print(lst)  # [10, 20, 30, 100, ['hello', 'world']]
lst.extend(lst2)  # Add more than one element at a time to the end of the list lst
print(lst)  # [10, 20, 30, 'hello', 'world']

insert() adds an element anywhere in the list

# Add an element anywhere
lst = [10, 20, 30]
print(lst)
lst.insert(1, 90)  # Add element 90 at index 1
print(lst)  # [10, 90, 20, 30]

Slice and add at least one element anywhere in the list

# Add at least one element anywhere in the list
lst = [10, 20, 30]
print(lst, id(lst))
lst3 = [True, False, 'hello']
lst[1:] = lst3  # Replace the element in the original list with the element in lst3 from the specified position
print(lst, id(lst))  # [10, True, False, 'hello'] 
# No new list objects are generated here

Deletion of list elements
remove() Deletes one element at a time, only the first element is deleted for duplicate elements, and a ValueError is thrown when the element does not exist

# Removes an element from the list
lst = [10, 20, 30, 40, 50, 60, 30]
lst.remove(30)
print(lst)  # [10, 20, 40, 50, 60, 30

pop() deletes an element at the specified index position, throws IndexError when the specified index does not exist, and deletes the last element in the list when the index is not specified

# Removes an element from the list based on the index
lst = [10, 20, 30, 40, 50, 60, 30]
lst.pop(1)
print(lst)  # [10, 30, 40, 50, 60, 30]

section

lst = [10, 20, 30, 40, 50, 60]
print(lst, id(lst))  # [10, 20, 30, 40, 50, 60] 2632700044992
new_list = lst[1:3]
print(new_list, id(new_list))  # [20, 30] 2632700031680
# The slicing operation generates a new list object, which is different from the original list id
# Replacing the element at the specified position with an empty element does not produce a new list
lst[1:4] = []
print(lst, id(lst))  # [10, 50, 60] 2632700044992

clear() clear the list
del delete list object

# Clear all elements in the list
lst = [10, 20, 30, 40, 50]
print(lst)  # [10, 20, 30, 40, 50]
lst.clear()  # Note that there is a () after clear
print(lst)  # []
# Delete entire list object
lst = [10, 20, 30, 40, 50]
print(lst)  # [10, 20, 30, 40, 50]
del lst
print(lst)  # NameError: name 'lst' is not defined. Did you mean: 'list'?

Modification of list elements
Assigns a new value to the element of the specified index
Assigns a new value to the specified slice

# Modify one value at a time
lst = [10, 20, 30, 40, 50]
print(lst)  # [10, 20, 30, 40, 50]
lst[2] = 100
print(lst)  # [10, 20, 100, 40, 50]

# Assigns a new value to the specified slice
lst[1:3] = [300, 400, 500, 600]
print(lst)  # [10, 300, 400, 500, 600, 40, 50]

Sorting operation of list elements
There are two common ways:
① Call sort() to sort all elements in the list in ascending order by default. You can specify reverse=True to sort in descending order
② Call the built-in function sorted(), and specify reverse=True to sort in descending order. The original list will not be changed

lst = [20, 40, 10, 90, 60]
print('List before sorting', lst, id(lst))  # List before sorting [20, 40, 10, 90, 60] 2709493622464
lst.sort()
print('Sorted list', lst, id(lst))  # Sorted list [10, 20, 40, 60, 90] 2709493622464
# Before and after sorting, the id of the list does not change

# Descending sort
lst.sort(reverse=True)
print(lst)  # [90, 60, 40, 20, 10]

Note: note the difference in the use of sort() and the built-in function sorted()

lst = [20, 40, 10, 90, 60]
print('List before sorting', lst, id(lst))  # List before sorting [20, 40, 10, 90, 60] 2162580367040
new_list = sorted(lst)
print(new_list, id(new_list))  # [10, 20, 40, 60, 90] 2162580353728
# Using the built-in function produces a new list object

desc_list = sorted(lst, reverse=True)
print('List in descending order', desc_list, id(desc_list))  # Descending list [90, 60, 40, 20, 10] 2162580352896

List generation
The formula that generates the list

# Syntax format: [i*i for i in range(1,10)] where i is a user-defined variable and i*i is an expression representing a list element
# Note: expressions representing list elements usually contain custom variables
lst = [i for i in range(1, 10)]
print(lst)  # [1, 2, 3, 4, 5, 6, 7, 8, 9]
lst2 = [i*i for i in range(1, 10)]
print(lst2)  # [1, 4, 9, 16, 25, 36, 49, 64, 81]

Topics: Python Back-end