summary
In actual development, it is often necessary to store a set (more than one) of data for later code to use. At this point, you may have heard of an Array, which can store multiple data one by one, and each element in the Array can be accessed through the Array subscript.
It should be clear that Python does not have arrays, but adds a more powerful list.
If the array is regarded as a container, the Python list is a factory warehouse.
Most programming languages support arrays, such as C language, C + +, Java, PHP, JavaScript, etc.
Formally, the list will place all elements in a pair of brackets [], and the adjacent elements are separated by commas, as shown below:
[element1, element2, element3, ..., elementn]
In the format, element1 ~ elementn represent the elements in the list. There is no limit on the number of elements, as long as they are the data types supported by Python.
In terms of content, a list can store any type of data such as integers, decimals, strings, lists, tuples, etc., and the types of elements in the same list can also be different. for instance:
["www.qinjl.com", 1, [2,3,4], 3.0]
You can see that the list contains string, integer, list and floating point data types at the same time.
Note that when using a list, although different types of data can be put into the same list, this is not usually done. Only the same type of data can be put into the same list, which can improve the readability of the program.
In addition, list is often used to refer to the list, because the data type of the list is list, which can be known through the type() function, for example:
>>> type( ["www.qinjl.com", 1, [2,3,4] , 3.0] ) <class 'list'>
You can see that its data type is list, which means it is a list.
Python creates lists (2 ways)
In Python, there are two methods to create lists, which are described below.
Create a list directly using []
After creating a list with [], it is generally assigned to a variable with = in the following format:
listname = [element1 , element2 , element3 , ... , elementn]
Where listname represents the variable name and element1 ~ elementn represents the list element.
For example, the lists defined below are legal:
num = [1, 2, 3, 4, 5, 6, 7] name = ["www.qinjl.com"] program = ["C language", "Python", "Java"]
In addition, when creating a list in this way, there can be multiple or none elements in the list, for example:
emptylist = [ ]
This indicates that emptylist is an empty list.
Use the list() function to create a list
In addition to using [] to create lists, Python also provides a built-in function list(), which can be used to convert other data types to list types. For example:
#Convert string to list list1 = list("hello") print(list1) Output:['h', 'e', 'l', 'l', 'o'] #Convert tuples to lists tuple1 = ('Python', 'Java', 'C++', 'JavaScript') list2 = list(tuple1) print(list2) Output:['Python', 'Java', 'C++', 'JavaScript'] #Convert dictionary to list dict1 = {'a':100, 'b':42, 'c':9} list3 = list(dict1) print(list3) Output:['a', 'b', 'c'] #Convert interval to list range1 = range(1, 6) list4 = list(range1) print(list4) Output:[1, 2, 3, 4, 5] #Create an empty list print(list()) Output:[]
Access list elements
List is a kind of Python sequence. We can use Index to access an element in the list (the value of an element is obtained), or we can use slice to access a group of elements in the list (a new sub list is obtained).
The format of using index to access list elements is:
listname[i]
Where listname represents the list name and i represents the index value. The index of the list can be positive or negative.
The format for accessing list elements using slices is:
listname[start : end : step]
Where, listname represents the list name, start represents the start index, end represents the end index, and step represents the step size.
The above two methods are in Python sequence It is explained in and will not be repeated here. It is only an example demonstration. Please see the following code:
url = list("www.qinjl.com") #Use an index to access an element in a list print(url[3]) #Use positive index print(url[-4]) #Use negative index #Use tiles to access a set of elements in a list print(url[9: 13]) #Use positive slice print(url[9: 13: 3]) #Specified Steps print(url[-6: -1]) #Use negative slices Output: . . ['.', 'c', 'o', 'm'] ['.', 'm'] ['j', 'l', '.', 'c', 'o']
Delete list
If the created list is no longer used, you can delete it with the del keyword.
In actual development, del is not often used to delete lists, because Python's built-in garbage collection mechanism will automatically destroy useless lists. Python will automatically recycle them even if developers do not delete them manually.
The syntax format of del keyword is:
del listname
Where listname indicates the name of the list to be deleted.
Python delete list instance Demo:
intlist = [1, 45, 8, 34] print(intlist) del intlist print(intlist) Output: [1, 45, 8, 34] Traceback (most recent call last): File "C:\Users\qinjl\Desktop\demo.py", line 4, in <module> print(intlist) NameError: name 'intlist' is not defined
Add elements to the list (3 methods)
Python sequence The first section tells us that multiple sequences can be connected by using the + operator;
List is a kind of sequence, so you can also use + to connect, which is equivalent to adding another list at the end of the first list.
See the following Demo:
language = ["Python", "C++", "Java"] birthday = [1991, 1998, 1995] info = language + birthday print("language =", language) print("birthday =", birthday) print("info =", info) Output: language = ['Python', 'C++', 'Java'] birthday = [1991, 1998, 1995] info = ['Python', 'C++', 'Java', 1991, 1998, 1995]
It can be found from the running results that using + will generate a new list, and the original list will not be changed.
+It is more used to splice lists, and the execution efficiency is not high. If you want to insert elements in the list, you should use the following special methods.
Add element with append() method
The append() method is used to append elements to the end of the list. The syntax format of this method is as follows:
listname.append(obj)
Where, listname represents the list of elements to be added; obj represents the data added to the end of the list. It can be a single element, a list, a tuple, etc.
l = ['Python', 'C++', 'Java'] #Append element l.append('PHP') print(l) Output:['Python', 'C++', 'Java', 'PHP'] #The tuple is appended, and the whole tuple is treated as an element t = ('JavaScript', 'C#', 'Go') l.append(t) print(l) Output:['Python', 'C++', 'Java', 'PHP', ('JavaScript', 'C#', 'Go')] #Append the list, and the whole list is also treated as an element l.append(['Ruby', 'SQL']) print(l) Output:['Python', 'C++', 'Java', 'PHP', ('JavaScript', 'C#', 'Go'), ['Ruby', 'SQL']]
As you can see, when passing lists or tuples to the append() method, the method will treat them as a whole and add them to the list as an element, thus forming a new list containing lists and tuples.
The extend() method adds an element
The difference between extend() and append() is that extend() does not treat the list or ancestor as a whole, but adds the elements contained in them to the list one by one.
The syntax format of the extend() method is as follows:
listname.extend(obj)
Where, listname refers to the list of elements to be added; obj represents the data added to the end of the list. It can be a single element, a list, tuples, etc., but it cannot be a single number.
l = ['Python', 'C++', 'Java'] #Append element l.extend('C') print(l) Output:['Python', 'C++', 'Java', 'C'] #By appending tuples, Yuanzu is split into multiple elements t = ('JavaScript', 'C#', 'Go') l.extend(t) print(l) Output:['Python', 'C++', 'Java', 'C', 'JavaScript', 'C#', 'Go'] #The list is appended, and the list is also split into multiple elements l.extend(['Ruby', 'SQL']) print(l) Output:['Python', 'C++', 'Java', 'C', 'JavaScript', 'C#', 'Go', 'Ruby', 'SQL']
insert() method inserts an element
The append() and extend() methods can only insert elements at the end of the list. If you want to insert elements in the middle of the list, you can use the insert() method.
The syntax format of insert() is as follows:
listname.insert(index , obj)
Where index represents the index value of the specified location. insert() inserts obj into the index element of the listname list.
When inserting a list or ancestor, insert() will also treat them as a whole and insert them into the list as an element, which is the same as append().
l = ['Python', 'C++', 'Java'] #Insert element l.insert(1, 'C') print(l) Output:['Python', 'C', 'C++', 'Java'] #Insert tuples, and the entire ancestor is treated as an element t = ('C#', 'Go') l.insert(2, t) print(l) Output:['Python', 'C', ('C#', 'Go'), 'C++', 'Java'] #Insert the list, and the whole list is treated as an element l.insert(3, ['Ruby', 'SQL']) print(l) Output:['Python', 'C', ('C#', 'Go'), ['Ruby', 'SQL'], 'C++', 'Java'] #Insert a string, and the entire string is treated as an element l.insert(0, "www.qinjl.com") print(l) Output:['www.qinjl.com', 'Python', 'C', ('C#', 'Go'), ['Ruby', 'SQL'], 'C++', 'Java']
Tip: insert() is mainly used to insert elements in the middle of the list. If you only want to append elements at the end of the list, it is more recommended to use append() and extend().
list delete elements (4 methods)
Deleting elements in the list is mainly divided into the following three scenarios:
-
Delete according to the index of the location of the element. You can use the del keyword or pop() method;
-
Delete according to the value of the element itself. You can use the remove() method provided by the list (list type);
-
To delete all the elements in the list, you can use the clear() method provided by the list (list type).
del deletes an element based on the index value
del is a keyword in Python, which is specially used to perform deletion. It can not only delete the whole list, but also delete some elements in the list.
del can delete a single element in the list. The format is:
del listname[index]
Where listname represents the list name and index represents the index value of the element.
del can also delete a continuous element in the middle. The format is:
del listname[start : end]
Where, start indicates the start index and end indicates the end index. del will delete the elements from the index start to end, excluding the elements at end (closed on the left and open on the right).
lang = ["Python", "C++", "Java", "PHP", "Ruby", "MATLAB"] #Use positive index del lang[2] print(lang) Output:['Python', 'C++', 'PHP', 'Ruby', 'MATLAB'] #Use negative index del lang[-2] print(lang) Output:['Python', 'C++', 'PHP', 'MATLAB'] del lang[1: 4] print(lang) Output:['Python', 'Ruby', 'MATLAB'] lang.extend(["SQL", "C#", "Go"]) del lang[-5: -2] print(lang) Output:['Python', 'C#', 'Go']
pop() deletes the element according to the index value
The pop() method is used to delete the element at the specified index in the list. The specific format is as follows:
listname.pop(index)
Where listname represents the list name and index represents the index value.
Note: if you do not write the index parameter, the last element in the list will be deleted by default, which is similar to the "out of stack" operation in the data structure.
nums = [40, 36, 89, 2, 36, 100, 7] nums.pop(3) print(nums) Output:[40, 36, 89, 36, 100, 7] nums.pop() print(nums) Output:[40, 36, 89, 36, 100]
Most programming languages provide a method corresponding to pop(), push(), which is used to add elements to the end of the list, similar to the "stack" operation in the data structure.
But Python is an exception. Python does not provide the push() method, because it can use append() instead of push().
remove() deletes according to the element value
In addition to the del keyword, Python also provides a remove() method, which will delete according to the value of the element itself.
It should be noted that the remove() method will only delete the first element with the same value as the specified value, and the element must be guaranteed to exist, otherwise a ValueError error will be raised.
nums = [40, 36, 89, 2, 36, 100, 7] #First delete 36 nums.remove(36) print(nums) Output:[40, 89, 2, 36, 100, 7] #Second deletion 36 nums.remove(36) print(nums) Output:[40, 89, 2, 100, 7] #Delete 78 nums.remove(78) print(nums) Output: Traceback (most recent call last): File "C:\Users\mozhiyan\Desktop\demo.py", line 9, in <module> nums.remove(78) ValueError: list.remove(x): x not in list
The last deletion will result in an error because 78 does not exist, so we'd better judge in advance when using remove() to delete elements.
clear() deletes all elements of the list
Python clear() is used to delete all elements of the list, that is, to empty the list
url = list("www.qinjl.com") url.clear() print(url) Output:[]
list modify elements
Modify a single element
Modifying a single element is very simple. You can assign a value to the element directly.
nums = [40, 36, 89, 2, 36, 100, 7] nums[2] = -26 #Use positive index nums[-3] = -66.2 #Use negative index print(nums) Output: [40, 36, -26, 2, -66.2, 100, 7]
After using the index to get the list element, the value of the element is changed by assigning = value.
Modify a set of elements
Python supports assigning values to a set of elements through slicing syntax.
In this operation, if the step size (step parameter) is not specified, Python does not require the number of newly assigned elements to be the same as the number of original elements;
This means that the operation can add or delete elements for the list.
nums = [40, 36, 89, 2, 36, 100, 7] #Modify the value of elements 1 ~ 4 (excluding element 4) nums[1: 4] = [45.25, -77, -52.5] print(nums) Output:[40, 45.25, -77, -52.5, 36, 100, 7]
If you assign a value to = = empty slice = = it is equivalent to inserting a new set of elements:
nums = [40, 36, 89, 2, 36, 100, 7] #Insert element in 4 places nums[4: 4] = [-77, -52.5, 999] print(nums) Output:[40, 36, 89, 2, -77, -52.5, 999, 36, 100, 7]
When using slicing syntax to assign values, Python does not support single values. For example, the following writing is wrong: num [4:4] = - 77
However, if string assignment is used, Python will automatically convert the string into a sequence, in which each character is an element. See the following code:
s = list("Hello") s[2:4] = "XYZ" print(s) Output:['H', 'e', 'X', 'Y', 'Z', 'o']
When using slice syntax, you can also specify the step size (step parameter), but at this time, the number of assigned new elements is required to be the same as the number of original elements, for example:
nums = [40, 36, 89, 2, 36, 100, 7] #The step size is 2 and the values are assigned to the 1st, 3rd and 5th elements nums[1: 6: 2] = [0.025, -99, 20.5] print(nums) Output:[40, 0.025, 89, -99, 36, 20.5, 7]
list find elements
Python list s provide index() and count() methods, both of which can be used to find elements.
index() method
The index() method is used to find the position of an element in the list (that is, the index). If the element does not exist, it will lead to ValueError error. Therefore, it is best to use the count() method to judge before finding.
The syntax format of index() is:
listname.index(obj, start, end)
Where listname represents the name of the list, obj represents the element to be searched, start represents the start position, and end represents the end position.
The start and end parameters are used to specify the search range:
-
start and end can be left blank, and the entire list will be retrieved;
-
If you only write start and not end, it means to retrieve the elements from start to the end;
-
If both start and end are written, the element between start and end is retrieved.
Example of index() method:
nums = [40, 36, 89, 2, 36, 100, 7, -20.5, -999] #Retrieves all elements in the list print( nums.index(2) ) Output: 3 #Retrieve elements between 3 and 7 print( nums.index(100, 3, 7) ) Output: 5 #Retrieve elements after 4 print( nums.index(7, 4) ) Output: 6 #Retrieve a non-existent element print( nums.index(55) ) Output: Traceback (most recent call last): File "C:\Users\qinjl\Desktop\demo.py", line 9, in <module> print( nums.index(55) ) ValueError: 55 is not in list
count() method
The count() method is used to count the number of times an element appears in the list. The basic syntax format is:
listname.count(obj)
Where listname represents the list name and obj represents the elements to be counted.
If count() returns 0, it means that the element does not exist in the list, so count() can also be used to judge whether an element in the list exists.
Usage example of count():
nums = [40, 36, 89, 2, 36, 100, 7, -20.5, 36] #Counts the number of occurrences of the element print("36 There it is%d second" % nums.count(36)) #Determine whether an element exists if nums.count(100): print("The element 100 exists in the list") else: print("The element 100 does not exist in the list") Output: 36 Three times The element 100 exists in the list
Tips and precautions for using list
Many list operation functions have been introduced earlier. The functions of many operation functions are very similar.
For example, the functions that add element functions include append() and extend(), and the functions that delete elements include clear(), remove(), pop(), and del keywords.
The usage of each function, the differences between some functions and some precautions in use are clarified by example demonstration.
Methods and differences of adding elements to list
Define two lists (list_1 and list_2 respectively), and operate the two lists with +, extend(), and append(), respectively. The result of the operation is assigned to res. The example code is as follows:
tt = 'hello' #Define a list that contains multiple types list_1 = [1,4,tt,3.4,"yes",[1,2]] print(list_1, id(list_1)) Output:[1, 4, 'hello', 3.4, 'yes', [1, 2]] 2251638471496 #Compare the usage and differences of several methods of adding elements to list list_2 = [6,7] res = list_1 + list_2 print(res,id(res)) print(list_1, id(list_1)) Output: [1, 4, 'hello', 3.4, 'yes', [1, 2], 6, 7] 2251645237064 [1, 4, 'hello', 3.4, 'yes', [1, 2]] 2665205552136 res = list_1.extend(list_2) print(res,id(res)) print(list_1,id(list_1)) Output: None 1792287952 [1, 4, 'hello', 3.4, 'yes', [1, 2], 6, 7] 2251638471496 res = list_1.append(list_2) print(res,id(res)) print(list_1,id(list_1)) Output: None 1792287952 [1, 4, 'hello', 3.4, 'yes', [1, 2], 6, 7, [6, 7]] 2251638471496
According to the output results, the following conclusions can be analyzed:
-
The list connected with "+" is the list_ The elements in 2 are placed in the list_ Res obtained after 1. And the memory address value of res is the same as that of list_1 is different, which indicates that res is a regenerated list, the original list_1 will not change.
-
The res obtained after using extend() is none. Indicates that extend has no return value and cannot use chained expressions. That is, extend must not be placed on the right side of the equation. Attention must be paid to it.
-
After extend() processing, list_ The content of 1 is the same as the res generated with the "+" sign. But list_ The address of 1 does not change before and after the operation, which indicates that the processing of extend only changes the list_1 without re creating a list. From this point of view, extend is more efficient than the "+" sign.
-
As can be seen from the result of append(), the function of append is to list_2 the whole is added to the list as an element_ 1 later, this is completely different from the functions of extend and "+".
list delete operation
Next, we will demonstrate the basic usage of del. The example code is as follows:
tt = 'hello' #Define a list that contains multiple types list1 = [1,4,tt,3.4,"yes",[1,2]] print(list1) Output:[1, 4, 'hello', 3.4, 'yes', [1, 2]] del list1[2:5] print(list1) Output:[1, 4, [1, 2]] del list1[2] print(list1) Output:[1, 4]
These three lines of output are the original content of list1, deleting part of the slice content and deleting the specified index content respectively. You can see that the del keyword deletes the specified content according to the specified position.
It should be noted that when using the del keyword, you must find out whether the deleted variables or data. For example, the following code demonstrates how to and delete variables:
tt = 'hello' # Define a list that contains multiple types list1 = [1, 4, tt, 3.4, "yes", [1, 2]] l2 = list1 print(id(l2), id(list1)) Output: 1765451922248 del list1 print(l2) Output:[1, 4, 'hello', 3.4, 'yes', [1, 2]] print(list1) Output: Traceback (most recent call last): File "C:\Users\qinjl\Desktop\demo.py", line 8, in <module> print(list1) NameError: name 'list1' is not defined
The output of the first line is the address of l2 and list1. You can see that they are the same, indicating that the assignment between l2 and list1 is only to pass the memory address.
Next, delete list1 and print l2. You can see that the memory data pointed to by l2 still exists, which indicates that del only destroys the variable list1 when deleting list1 and does not delete the specified data.
In addition to deleting variables, other deletions are to delete data, such as clearing all the data in the list. The implementation code is as follows:
tt = 'hello' #Define a list that contains multiple types list1 = [1,4,tt,3.4,"yes",[1,2]] l2 = list1 l3 = l2 del l2[:] print(l2) print(l3) Output: [] []
You can see that l3 and l2 execute the same memory address. When l2 is cleared, the content of l3 is also cleared. This indicates that the data in memory has really changed.
In addition, in the actual process, even if the del keyword is used to delete the specified variable, and the memory occupied by the variable is not used by other variables, this memory space will not be really reclaimed and reused by the system, but will be marked as invalid memory.
If you want the system to reclaim this available memory, you need to use the collect() function in the gc library. For example:
#Import gc Library import gc tt = 'hello' #Define a list that contains multiple types list1 = [1,4,tt,3.4,"yes",[1,2]] del list1 #Reclaim memory address gc.collect()
In front Python caching mechanism As mentioned in the previous section, the system will store some variables in memory in order to improve performance.
In this mechanism, when multithreading is concurrent, a large number of memory occupied variables generated by the program cannot be released, or some global variables that no longer need to be used occupy a large amount of memory, resulting in insufficient memory in subsequent runs. At this time, you can use the del keyword to destroy variables, let GC reclaim memory, and improve the performance of the system.
The list implements stacks and queues
Queue and stack are two data structures, in which variables are stored in a fixed order. The difference between them lies in the access order of data:
-
Queue: the data stored first is taken out first, i.e. "first in, first out".
-
Stack: the last stored data is taken out first, that is, "last in, first out".
Considering that the storage of list type data itself is sequential, and the internal elements can be of different types, it is very suitable for the implementation of queue and stack.
list implementation queue
The implementation method of using list to simulate queue function is to define a list variable, use the insert() method when saving data, and set its first parameter to 0, that is, insert data from the front every time;
When reading data, pop() is used to pop up the last element of the queue.
In this way, the access order of data in the list conforms to the characteristics of "first in, first out". The implementation code is as follows:
# Define an empty list as a queue queue = [] # Inserts an element into the list queue.insert(0, 1) queue.insert(0, 2) queue.insert(0, "hello") print(queue) print("Take an element:", queue.pop()) print("Take an element:", queue.pop()) print("Take an element:", queue.pop()) Output: ['hello', 2, 1] Take an element: 1 Take an element: 2 Take an element: hello
list implementation stack
The implementation method of using list to simulate stack function is to store data by using append() method; Use the pop() method to read the data.
When the append() method stores data into the list, it adds data to the last side every time, which is just the opposite to the insert() method in the previous program.
for instance:
# Define an empty list as a stack stack = [] stack.append(1) stack.append(2) stack.append("hello") print(stack) print("Take an element:", stack.pop()) print("Take an element:", stack.pop()) print("Take an element:", stack.pop()) Output: [1, 2, 'hello'] Take an element: hello Take an element: 2 Take an element: 1
The collections module implements stacks and queues
In the previous example of using list to implement queue, the part of inserting data is implemented through the insert() method. This method is not efficient, because every time a data is inserted from the beginning of the list, all elements in the list have to move back one position.
A relatively more efficient method is introduced here, that is, the deque structure in the collections module of the standard library is used. It is designed to store and read a special list quickly at both ends, which can be used to realize the functions of stack and queue.
from collections import deque queueAndStack = deque() queueAndStack.append(1) queueAndStack.append(2) queueAndStack.append("hello") print(list(queueAndStack)) Output:[1, 2, 'hello'] # To realize the queue function, take an element from the queue. According to the first in first out principle, 1 should be output here print(queueAndStack.popleft()) Output: 1 # Realize the stack function, take an element from the stack, and output hello here according to the last in first out principle print(queueAndStack.pop()) Output: hello # Print the list again print(list(queueAndStack)) Output:[2]