Python – List
1 Definition
Used to store any number and any type of data collection. List is a built-in data type in Python. Standard syntax format: 1. a = [10,20,30,40] 2. a = [10,20,abc’,True]
is an ordered collection in which elements can be added or deleted at any time. The identifier is square brackets [ ].
2 Create
2.1 Basic syntax creation
a=[10,20,'yangyaqi','Shijiazhuang University',True] a
[10, 20, yangyaqi’,Shijiazhuang University’,True]
a=[]
[]
2.2 list() function creates a list
Use list() to convert any iterable data into a list.
When using the list() function to create a list, be sure to pay attention to the double brackets.
In Python, we can convert other similar objects like strings, tuples, dictionaries, and sets into lists using the list() function
b=list() #Create an empty list
b=list(range(10)) b
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
this_list = list(('apple', 'banana', 'cherry')) this_list
[apple’, banana’, cherry’]
this_list=list('apple') this_list
[a’, p’, p’, l’, e’]
3 Common methods
Method | Key points | Description |
---|---|---|
list.append(x) | Add element | Add element x to the end of list |
list.extend(aList) | Add elements | Add all elements of list alist to the end of list |
list.insert(index,x) | Add element | Insert element x at the specified position index in list list |
list.remove(x) | Delete element | Delete the first occurrence of the specified element x in the list list |
list.pop(lindex]) | Delete element | Delete and return the element at the index specified by list, The default is the last element |
list.clear() | Delete all elements | Delete all elements of the list , it is not deleting the list object |
list.index(x) | Accessing the element | Return to the first index position of “left”>Returns the number of times the specified element x appears in the list |
len(list) | List length | Return the number of elements contained in the list |
list.reverse() | Reverse the list | All elements flip in place |
list.sort() | Sort | All elements in place Sort |
list.copy() | Shallow copy | Return a shallow copy of the list object |
4 Operations
4.1 Element level
4.1.1 Extraction of elements
Offset:
The offset of the list starts from 0
The square brackets with offset after the list name correspond to the element at the corresponding position.Position list by offset
Same goes for nested lists
4.1.2 Modification of elements
Use assignment statements to modify
4.1.3 Addition of elements
+ Operator operations
It does not really add elements at the end, but creates a new list object; the elements of the original list and the elements of the new list are copied to the new list object in turn. This will involve a lot of copy operations and is not recommended for operating a large number of elements.
append.function
Modifying the list object in place is the real way of adding new elements to the end of the list. It is the fastest and is recommended.
extend() method
Adds all elements of the target list to the end of this list, which is an in-place operation and does not create a new list object.
insert() inserts elements
Use the insert() method to insert the specified element into any specified position in the list object. This will cause all elements behind the insertion position to move, which will affect the processing speed. Try to avoid it when a large number of elements are involved. Functions similar to this kind of movement include: remove(), pop(), and del(). When deleting non-tail elements, they will also move elements behind the operation position.
extend() method
Adds all elements of the target list to the end of this list, which is an in-place operation and does not create a new list object.
Function: Put an element in brackets to add the element to the end of the list
The format is: list name append0
4.1.4 Deletion of elements
del method
a=[100,200,888,300,400] del a[1] a[100, 888, 300, 400]
pop method
Delete and return the element at the specified position. If the position is not specified, the last element in the list will be operated by default.
a=[10,20,30,40,50] a.pop() a[10, 20, 30, 40]
remove() method
Delete the first occurrence of the specified element, and throw an exception if the element does not exist.
a = [10,20,30,40,50,20,30,20,30] a.remove(20) #20 here is data, not index a[10, 30, 40, 50, 20, 30, 20, 30]
Function: Delete list elements
The format is: del list name offset
4.2 List level
4.2.1 Slicing of lists
Extract a continuous piece of data from the list and generate a new list
Positioning the list range by offset
The range of [1:3] is 1<=x<3, the header does not include the tail
The values around the colon do not need to be filled in. If there is no value on either side of the colon, the value will be taken to the bottom
4.2.2 Modification of list
Use assignment statements directly
4.2.3 Addition of list
Use the operator +
Note: The symbol + can only be used to merge between lists
4.2.4 List deletion
Use del
4.2.5 List traversal
for obj in listObj: print(obj)for x in a: print(x,end="#")10#20#30#40#50#20#30#20#30#
4.2.6 Copy all elements of the list to a new list object
list1 = [30,40,50] list2 = list1list1 = [30,40,50] list2 = [] + list1
4.2.7 List sorting
sort method
a.sort()sorted method: Returns a new list without modifying the original list.
a = sorted(a)reversed() returns an iterator: it supports reverse order, does not make any modifications to the original list, and just returns an iterator object arranged in reverse order.
c = reversed(a)
5 range() creates a list of integers
range() can help us create a list of integers very conveniently, which is extremely useful in development. for:
start parameter: optional, indicating the starting number. Default is 0
end parameter: required, indicating the ending number.
step parameter: optional, indicating step size, default is 1
range() in python3 returns a range object, not a list. We need to convert it into a list object through the list() method.
Syntax format: range([start,] end [,step])
list(range(3,15,2))
[3, 5, 7, 9, 11, 13]
6 List comprehension
List comprehension is a simple and powerful tool in Python, a shortcut for creating list objects. It allows us to generate a list with a single line of code, and filter, transform, and combine elements during the generation process.
Grammar format
[expression1 if condition else expression2 for item in iterable]
result = [] for item in iterable: if condition1: result.append(expression1(item)) else: result.append(expression2(item))
numbers = [1, 2, 3, 4, 5] even_odd = ['even' if num % 2 == 0 else 'odd' for num in numbers] print(even_odd)
[odd’, even’, odd’, even’, odd’]
[expression for item in iterable]
Among them, expression is a calculation expression that generates list elements, item is each element in the iterable object, and iterable is an iterable object (such as a list, tuple, set, etc.), which is equivalent to:
result = [] for item in iterable: result.append(expression(item))
[expression for item in iterable if condition]
result = [] for item in iterable: if condition: result.append(expression(item))
#Filter the list of even numbers: even_numbers = [x for x in range(1, 11) if x % 2 == 0] print(even_numbers)
[2, 4, 6, 8, 10]
7 Multidimensional List
a=[ ["st1",18,30000,"Beijing"], ["st2",19,20000,"Shanghai"], ["st3",20,10000,"Shenzhen"],]#Nested loop prints all the numbers in the two-dimensional list for m in range(3): for n in range(4): print(a[m][n],end="\t") print()#After printing a line, wrap itst1 18 30000 Beijing
st2 19 20000 Shanghai
st3 20 10000 Shenzhen