Hello, I am Ma Nongfei ge, thank you for reading this article, welcome one button three lian oh. This article is divided into ten chapters to introduce the data type in the list (list) and tuple (tuple), from the use of the bottom layer implementation, package you are satisfied with the dry goods, recommended collection, need to use often see. If you have any questions or needs, please feel free to leave a message.
Shallow: Introduction to lists
A list, as one of the Python sequence types, is also a block of memory used to store multiple elements in a certain order. Its data structure is:
[element1, element2, element3, ..., elementn]
Copy the code
Element1 ~elementn represents the elements in the list. There is no limit to the data format of the element, as long as Python supports the data format can be inside. At the same time, because the list supports automatic expansion, it can change the sequence, that is, it can change the list dynamically, that is, it can modify, add, delete list elements. Take a look!
Shallow: List operation
The first introduction is the operation of the list: including the creation of the list, the deletion of the list and so on! There are two ways to create a list: The first way: wrap the elements in the list with [], and separate each element with a comma. The element type is unlimited and each element in the same list can have a different type, but this is not recommended because it is very inconvenient to traverse the list if each element has a different data type. It is recommended that a list only contain elements of the same type.
list=[element1, element2, element3, ..., elementn]
Copy the code
For example: test_list =[‘ test ‘, 2, [‘ nonfly ‘, ‘small ‘], (12, 23)] PS: empty list is defined as list=[] second way: create a list by using the list(iterable) function, which is a built-in Python function. The arguments passed to this function must be iterable sequences such as strings, lists, tuples, etc. If iterable is passed empty, an empty list is created. Iterable cannot pass only one number.
classmates1 = list('Code Nongfei')
print(classmates1)
Copy the code
The generated list is: [‘ code ‘, ‘nong ‘,’ fly ‘, ‘brother ‘]
Shallow: Adds elements to the list
There are four ways to add elements to a list: first, concatenate multiple lists using the **+ operator. This is equivalent to adding another list at the end of the first list. The syntax is listname1+ Listname2
name_list = ['Code Nongfei'.'lil'.Little Big]
name_list2 = ['python'.'java']
print(name_list + name_list2)
Copy the code
The output is: [‘ Code Nongfei ‘, ‘xiao Wei ‘,’ Xiao Wei ‘, ‘Python ‘,’ Java ‘], and you can see that each element in name_list2 has been added to the end of name_list. The second: Append () is used to add elements to the end of the list. The syntax is listName.append (p_object), where listName represents the list of elements to be added, p_object represents the element to be added to the end of the list, It can be a string, a number, or a sequence. Here’s an example:
name_list.append('Adam')
print(name_list)
name_list.append(['test'.'test1'])
print(name_list)
Copy the code
The results are as follows:
Farmers flying elder brother [' of ', 'lil', 'small wei', 'Adam'] [' yards farmers flying elder brother ', 'lil', 'small wei', 'Adam' [' test ', 'test1']]Copy the code
You can see that the elements to be added were successfully added to the end of the original list. And when the added element is a sequence, the sequence is treated as a whole. Extend () extends the extend() method in the same way as append(), which adds elements to the end of the list. The type of the element requires only the data types supported by Python. Unlike the append() method, however, when the added elements are sequences, the extend() method does not treat the list as a whole, but adds each element to the end of the list. Again, the above example:
name_list = ['Code Nongfei'.'lil'.Little Big]
name_list.extend('Adam')
print(name_list)
name_list.extend(['test'.'test1'])
print(name_list)
Copy the code
The results are as follows:
Farmers flying elder brother [' of ', 'lil', 'small wei', 'A', 'd', 'A', 'm'] [' yards farmers flying elder brother, 'lil', 'small wei', 'A', 'd', 'A', 'm', 'test', 'test1']Copy the code
As you can see from the results, each character in the string is appended to the end of the list as an element when a string is added, and each element in the list is appended to the end when a list is added. Each of the previous insert methods can only insert elements at the end of the list, and cannot insert elements at the specified position in the list. The insert() method is formally designed to deal with this problem. Insert (index, p_object) where index represents the index value at the specified position. Insert () will insert P_object at the position of the index element in the listName list. As with the append() method, if the element to be added is a sequence, insert() inserts that sequence as a whole at the specified location in the list. Here’s an example:
name_list = ['Code Nongfei'.'lil'.Little Big]
name_list.insert(1.'Jack')
print(name_list)
name_list.insert(2['test'.'test1'])
print(name_list)
Copy the code
The results are as follows:
['Code Nongfei'.'Jack'.'lil'.Little Big]
['Code Nongfei'.'Jack'['test'.'test1'].'lil'.Little Big]
Copy the code
Shallow: Modifies the elements in the list
Having said how to add elements to a list, let’s take a look at how to modify the list’s associated elements. There are two ways to modify a list element: First, modify a single element: You can modify a single element by reassigning the element on an index. Listname [index]=newValue; listName [index]=newValue; Here’s an example:
name_list = ['Code Nongfei'.'lil'.Little Big]
name_list[1] = 'Sarah'
print(name_list)
Copy the code
Run result: [‘ nongfeig ‘, ‘Sarah’, ‘Xiaowei ‘] It can be seen from the result that the element value at index 1 has been successfully changed to Sarch. The second: Listname [start:end:step], where listName indicates the name of the list, start indicates the start position, end indicates the end position (not included), step indicates the step size, If the step size is not specified, Python does not specify the same number of newly assigned elements as the original, which means that this operation can either add or remove elements from the list. Here’s an example:
name_list = ['Code Nongfei'.'lil'.Little Big]
name_list[0:1] = ['flying elder brother'.'cool']
print(name_list)
Copy the code
The result is: [‘ feige ‘, ‘niubi ‘,’ Xiaowei ‘, ‘Xiaowei ‘]. The result shows that the element value at index 0 in the original list has been replaced by Feige and niubi has been inserted.
Five shallow: Deletes elements in the list
There are four ways to delete elements from a list. The del keyword is used to delete a single element from an index, del listName [index], or to delete multiple elements from a slice. End], where listname indicates the listname, start indicates the start index, end indicates the end index, del deletes elements from the index start to end, but does not include elements in the end position. Here’s an example:
name_list = ['Code Nongfei'.'lil'.Little Big."Superman"]
name_list2 = name_list
print('Original name_list={0}'.format(name_list))
print('Original name_list2={0}'.format(name_list2))
Select * from index 0 where index 1 is 1 and index 0 where index 1 is 1
del name_list[0:2]
print('Name_list ={0}'.format(name_list))
print('Name_list2 ={0}'.format(name_list2))
del name_list
print('Name_list2 ={0}'.format(name_list2))
Copy the code
The results are as follows:
Original name_list = [' yards farmers flying elder brother ', 'lil', 'small wei', 'superman'] original name_list2 = [' yards farmers flying elder brother ', 'lil', 'small wei', 'superman'] using the del after removing elements name_list = [' small wei, Name_list2 =[' Small size ', 'Superman ']Copy the code
If you use del to delete a list element, you actually delete the memory data. If you use del to delete a list element, you only delete the variable. The memory data pointed to by name_list2 still exists. The pop() method, which deletes an element based on the index value, has the following syntax: Listname.pop (index), where listname indicates the listname and index indicates the index value. If the index parameter is not specified, the last element in the list is deleted by default, similar to the unstack operation in data structures. Here’s an example:
name_list = ['Code Nongfei'.'lil'.Little Big."Superman"]
Delete the element at the end of the list
name_list.pop()
print(name_list)
# drop the element at the specified position using pop(I) where I is the index position
name_list.pop(1)
print(name_list)
Copy the code
The results are as follows:
[' Ma Nongfei Ge ', 'Xiao Wei ',' Xiao Wei '] [ma Nongfei Ge, 'Xiao Wei ']Copy the code
Remove () the syntax structure of the remove() method is listName.remove (object), where listName indicates the name of the list and object indicates the name of the element to be deleted. Note that ValueError is raised if the element does not exist in the list. Here’s an example:
name_list = ['Code Nongfei'.'lil'.Little Big."Superman"]
name_list.remove(Little Big)
print(name_list)
Copy the code
The result is: [‘ Yard non Fly brother ‘, ‘small wei ‘,’ Superman ‘]. Clear () : clear() : clear() : clear() : clear() : clear() : clear() : clear() : clear() : clear(); Here’s an example:
name_list = ['Code Nongfei'.'lil'.Little Big."Superman"]
name_list.clear()
print(name_list)
Copy the code
The result is: [], you can see that all the elements in the list are cleared.
Shallow: Finding and accessing elements in a list
After the fifth shallow-list element deletion, I’m a little tired. Proceed to the sixth shallow! Look at the lookup and access of elements in the list. With this in mind, we’re done with the list.
Access the elements in the list
There are two ways to access elements in a list, one is to access a single element through index positioning, and the other is to access multiple elements through slicing. The first is to access a single element by indexing. The syntax structure is listName [index], where ListName indicates the name of the list and index indicates the index value of the element to be searched. Listname [start:end:step]; listName [start:end:step]; Listname indicates the name of the list, start indicates the start index, end indicates the end index (excluding the end position), and step indicates the step size. Here’s another example:
list = ['Code Nongfei'.'lil'.Little Big.123]
print(list[0]) Print the first element of the list
print(list[1:3]) Print the second to third elements
print(list[2:)Print all elements from the third to the end of the list
Copy the code
The results are as follows:
[' Xiao Wei ', 'Xiao Wei '] [' Xiao Wei ', 123]Copy the code
Find the position of an element in a list index()
The indext() method finds the position of an element in the list (that is, the index) and raises ValueError if the element does not exist in the list. Index (object, start, end) where ListName indicates the name of the list, object indicates the element to be searched, start indicates the start index, and end indicates the end index(excluding).
Name_list = [' yards farmers flying elder brother ', 'lil', 'small wei', 'superman'] print (name_list. Index (' lil '0, 2))Copy the code
The run result is: 1
Seven shallow: list using skills and notes
Leave a blank here, welcome to leave a message to tell me, first look at a picture to relax!!If you feel better after seeing the picture, let’s continue to study it.
The differences between methods in Python’s new elements
The + operator, the append method, and the extend method all add elements, so what’s the difference? I’ll give you an example;
Name_list = [' nongfei ', 'xiaowei ',' Xiaowei ', [' superman '] name_list2 = [' bull devil '] name_list3 = name_list + name_list2 print(" original name_list ={0}; Format (name_list, id(name_list)) print(" name_list3 ={0}; Format (name_list3, id(name_list3)) print(" name_list {0}; Format (name_list, id(name_list))) name_list4 = name_list.append(' ') print(' ') name_list4 ={0}; Format (name_list4, id(name_list4))) print(" append ={1}'; Format (name_list, id(name_list))) name_list5 = name_list.extend(' new_list ') print(' new_list '={0}; Format (name_list4, id(name_list4)) print(" name_list value {0}; Format (name_list, id(name_list))Copy the code
The results are as follows:
Original name_list value =[' Nongfei ', 'Xiao Wei ',' Xiao Wei ', 'Superman ']; Memory address =2069467533448 use + operator name_list3 value =[' nonfeige ', 'xiaowei ',' Xiaowei ', 'Superman ',' Cow Devil ']; Memory address =2069467533896 name_list value [' nongfei ', 'xiaowei ',' Xiaowei ', 'Superman '] with + operator; Memory address =2069467533448 Name_list4 =None after append; Memory address =2012521616 name_list value after append method [' nongfeige ', 'xiaowei ',' Xiaowei ', 'Superman ',' Cow Monster ']; Memory address =2069467533448 Name_list5 =None after extend; Memory address = 2012521616 name_list after using the extend the value of the [' yards farmers flying elder brother ', 'lil', 'small wei', 'superman', 'but the king bull', 'cow', 'magic', 'the king']. Memory address =2069467533448Copy the code
The following points can be seen from the running results:
- Using the + operator creates a new list with a different address than the original list, and the contents of the original list do not change.
- The append and extend methods both modify the contents of the original list and return no value, so neither can use chained expressions.
- When the element to be added is a list, the Append method treats the list as a whole, while extend does not.
Hachshallow: An introduction to tuples
With lists out of the way, let’s look at another important sequence, a tuple. Like a list, a tuple is a series of elements sorted by a particular book. The most important difference from a list is that a tuple is an immutable sequence, meaning that once a tuple is created, its elements cannot be changed.
How tuples are created
The syntax for creating tuples with () is tuplename=(element1,element2,…. ,elementn), where tuplename represents the variable name of the tuple and element1~elementn represents the elements in the tuple. Parentheses are not required, and as long as elements are separated by commas, Python treats them as tuples. Here’s an example:
Create a tuple
tuple_name = ('Code Nongfei'.'lil'.Little Big."Superman")
print(tuple_name)
# remove the parentheses to create a tuple
tuple2 = 'Code Nongfei'.'lil'.Little Big."Superman"
print(type(tuple2))
Copy the code
The results are as follows:
(' Nongfei ', 'Xiaowei ',' Xiaowei ', 'Superman ')Copy the code
The iterable argument must be an iterable sequence, such as a string, a list, a tuple, or a tuple. The same iterable cannot pass a number. Here’s an example:
name_list = ['Code Nongfei'.'lil'.Little Big."Superman"]
print(tuple(name_list))
print(tuple('Code Nongfei'))
Copy the code
The results are as follows:
(' Ma Nong Fei Ge ', 'Xiao Wei ',' Xiao Wei ', 'Superman ')Copy the code
Because tuples are immutable sequences, there is no way to modify the element correlation, only the elements in a tuple can be viewed. Tuplename [index] Tuplename [index] Tuplename [index] Tuplename [index] Tuplename [start:end:step] parameter description is not repeated here. Again, to illustrate:
Print (tuple_name[1]) print(tuple_name[1]) print(tuple_name[1]) Print (tuple_name[0:2])Copy the code
The results are as follows:
Xiao Wei (' Ma Nong Fei Ge ', 'Xiao Wei ')Copy the code
Elements in a tuple cannot be modified, but a new tuple can be generated by +.
Shallow nine: the difference between tuples and lists
After finishing the front eight shallow, also a little tired. Let’s move on to the difference between tuples and lists. Why does Python set up another data structure like a tuple? Can’t a tuple’s list of functions be satisfied? Therefore, this shallow is mainly introduced the advantages of tuples, existence is reasonable, ha ha ha. The difference between:
- Can elements be modified?
Elements in a list can be modified, but elements in a tuple cannot. If you force an element in a tuple, you get the following error:
TypeError: 'tuple' object does not support item assignment
Copy the code
- Space occupied by storing the same data
The number of bytes required to initialize an empty list and an empty tuple is shown below
>>> listdemo = []
>>> listdemo.__sizeof__()
40
>>> tupleDemo = ()
>>> tupleDemo.__sizeof__()
24
Copy the code
You can see that tuples take up 16 bytes less than lists because lists are dynamic and need to store Pointers to the corresponding elements (8 bytes), and because the elements in the list are mutable, you need to store additional allocated lengths (8 bytes). But for tuples, the situation is different. The length of the tuple is fixed, and the storage element is immutable, so the storage space is also fixed. In general, the storage performance of tuples is due to lists, which take up less space to store the same data. 3. Time required to initialize the same data. If you think about a tuple or a list of the same data, which is faster? Is it a tuple or a list? Most people will choose tuples, but how fast are tuples? Here is an example: the same initialization elements are 1,2,3,4 sequences.
(python-demo) root$python3 -m timeit 'x=(1,2,3,4)' 10000000 loops, best of 3: 0.029 usec per loop (python-demo) root$python3 -m timeit 'x=[1,2,3,4]' 10000000 loops, best of 3: 0.165 usec per loopCopy the code
It took 0.029 seconds to initialize a tuple and 0.165 seconds to initialize a list, so it can be concluded that the time required to initialize a list and a tuple of the same element is more than 5 times faster than the list.
summary
Tuples have the following advantages: Tuples are faster to access and process than lists, and require less space to store the same content.
One deep: low-level implementation of lists and tuples
Nine shallow has been completed, finally let’s have a more in-depth exchange. To know why is to know why. Without further ado, let’s take a look at the underlying implementation of lists and tuples at the source level. First, let’s analyze the list. Its specific structure is as follows:
typedef struct {
PyObject_VAR_HEAD
/* Vector of pointers to list elements. list[0] is ob_item[0], etc. */
PyObject **ob_item;
/* ob_item contains space for 'allocated' elements. The number * currently in use is ob_size. * Invariants: * 0 <= ob_size <= allocated * len(list) == ob_size * ob_item == NULL implies ob_size == allocated == 0 * list.sort() temporarily sets allocated to -1 to detect mutations. * * Items must normally not be NULL, except during construction when * the list is not yet visible outside the function that builds it. */
Py_ssize_t allocated;
} PyListObject;
Copy the code
PS: List implementation source files are listObject.h and listObject.c. A list is essentially a continuous array of variable length. Tokens ob_item is a pointer list, each pointer points to the element in the list and allocated space is used to store the amount of space currently allocated to the list. Note that allocated space is different from the actual size of the list, the actual size of the list is the result returned by Len (list), ob_size in the above comment, which means how many elements are actually stored in the list. In order to optimize the storage structure and avoid reallocating memory every time additional elements are added, Allocated space is usually larger than OB_size. Their relationship is 0 <= ob_size <= allocated. Python3.7 tuple: Python3.7 tuple: Python3.7 tuple
typedef struct {
PyObject_VAR_HEAD
PyObject *ob_item[1];
/* ob_item contains space for 'ob_size' elements. * Items must normally not be NULL, except during construction when * the tuple is not yet visible outside the function that builds it. */
} PyTupleObject;
Copy the code
PS: tuple implementation source files are tupleObject.h and tupleObject.c. A tuple is like a list in that it is essentially an array, but of a fixed size. Unlike arrays, Python’s tuple has a number of optimizations to make it more efficient in programs.
conclusion
This article took a closer look at lists and tuples in Python’s built-in data types. Lists, in particular, have many ways to add and delete elements, and many different methods need to be used with special care. For scenarios that do not involve modifying elements, tuples are preferred. Because it performs better and takes up less space.
The whole network with the same name [code nongfei brother]. Thank you again for reading this article.