Lists and tuples have been well studied in the basics chapter , You should keep a basic impression of lists and tuples , Is an ordered collection that can place any data type , Or as a container .
The two most direct differences between them are , The length and size of the list are not fixed , variable , Tuple length is fixed , immutable .
In many places , Would call this distinction dynamic And static state .
The most common mistake here is to assign or modify values to tuples , The error message is as follows , You need to know why ?
TypeError: 'tuple' object does not support item assignment
How to add data to tuples , I think you should know better , Is to create a new tuple , Splice the new data with the old data , Get it done .
# Dream eraser Special anti - Crawler comments my_old_tuple = (1, 2, "a", "b") my_new_tuple = ("c", "d") my_tuple = my_old_tuple+my_new_tuple print(my_tuple)
For the basic part , What's more, please pay attention to , If a tuple has only one element , It must be written like this (1,)
, Do not omit commas , The data type in brackets is omitted , The final result is the data of that data type .
Lists and tuples are ordered , Order can slice , And slice remember Head and tail The operation of , For example, the following code .
my_tuple = my_old_tuple+my_new_tuple print(my_tuple[1:3])
When I first learned slicing , A common mistake is as follows , The cause of this error is ,[]
In brackets :
Written in other symbols .
TypeError: tuple indices must be integers or slices, not tuple
Both lists and slices support Negative index Value , But you need to know that the negative index is from -1
At the beginning , Why? ? Think about it for yourself .
Mutter in a low voice : It's not because 0 only one
The two can also be converted to each other , The transformation applies built-in functions list
and tuple
, Follow the function , Both lists and tuples have built-in functions that can be applied , This part is the first time to learn snowball , We've done it all , Very simple knowledge points .
Run the following code to see the running results , The list is consistent with the number of tuple elements .
my_list = ["a", "b", "c"] print(my_list.__sizeof__()) my_tuple = ("a", "b", "c") print(my_tuple.__sizeof__())
The output results are different , Lists and tuples of the same element data , The system allocates more space to the list
64 48
The first knowledge point is __sizeof__()
: Indicates the amount of space allocated by the printing system .
Next, let's do some basic tests , Check how the system allocates space from the list .
my_list = [] print(" Initialization size ",my_list.__sizeof__()) my_list.append("a") print(" Additional 1 Size after elements ",my_list.__sizeof__()) my_list.append("b") print(" Additional 2 Size after elements ",my_list.__sizeof__()) my_list.append("c") print(" Additional 3 Size after elements ",my_list.__sizeof__()) my_list.append("d") print(" Additional 4 Size after elements ",my_list.__sizeof__()) my_list.append("e") print(" Additional 5 Size after elements ",my_list.__sizeof__())
The running result is :
Initialization size 40 Additional 1 Size after elements 72 Additional 2 Size after elements 72 Additional 3 Size after elements 72 Additional 4 Size after elements 72 Additional 5 Size after elements 104
After adding an element , The size has become 72, And then it goes up in a row 4 Elements , The size of the system allocation has not changed , The earth 5 Elements , added 32 Byte space , So we can draw a conclusion :
The list will be added at one time 4 Space of elements , When the space is used up , Will continue to increase .
The principle of the above code :
The list is essentially , It's a dynamic array , The list is not the real data stored , It is the address of each element in memory ( quote ), Because the list store is a reference to an element , So the memory space occupied by the reference is the same , That is to say 8 Bytes , And it can store different types of data .
stay 64 Bit in the operating system , Address occupancy 8 Bytes , If your computer is 32 position , That address takes up 4 Bytes , Just pay attention .
Simply speaking , Tuples are used to fix the data of element contents , Lists are used for variable data , I hope the memory is simpler , You can write it down as if you only need 2、3 Elements , Just use tuple
, Elements are used when there are many namedtuple
, It's a function .
Use namedtuple
You need to import .
from collections import namedtuple help(namedtuple)
The function prototype is as follows :
namedtuple(typename, field_names, *, rename=False, defaults=None, module=None) # Returns a new subclass of tuple with named fields.
Write a piece of code first :
from collections import namedtuple Point = namedtuple('Point', ['x', 'y']) p = Point(10, 20) print(p.x) print(p.y)
The first two parameters need to be simply learned .
typename
: String type parameters , This parameter is understood to be a little bit convoluted , Post an official explanation ,namedtuple()
According to this typename
, Create a subclass and return the class name , For example, in the test code above Point
, The created class name is Point
, The second parameter is the future class attribute .field_names
: Used to name each element of the tuple created , You can pass in lists or tuples , for example ['a', 'b']
、(a,b)
, Can also be passed in 'a b'
or 'a,b'
This single string separated by commas or spaces . In the above, if you want to see the process of class construction , You can add parameters verbose
, But this parameter is also described on the official website , Some versions are not supported , stay Python 3.7 Then there is no such attribute .
Changed in version 3.6: The verbose and rename parameters became keyword-only arguments. Changed in version 3.6: Added the module parameter. Changed in version 3.7: Removed the verbose parameter and the _source attribute. Changed in version 3.7: Added the defaults parameter and the _field_defaults attribute.
Initializing an empty list is done using list() Or use []
This content can use the following code to test the efficiency .
import timeit a = timeit.timeit('a=list()', number=10000000 ) b = timeit.timeit('a=[]', number=10000000 ) print(a) print(b)
Running results :
1.6634819 0.5888171999999998
The conclusion is that []
Faster , because list()
It's a function call , The efficiency must be lower .
With the above function , You can also test the same elements when initializing lists and tuples , Which is more efficient .
import timeit a = timeit.timeit('a=("a","b","c")', number=10000) b = timeit.timeit('b=["a","b","c"]', number=10000) print(a) print(b)
The operation results are as follows :
# Initialize tuples 0.0005571000000000048 # Initialization list 0.002022099999999999
This blog , It mainly reviews some basic contents of lists and tuples , And explore the difference between list and tuple in system allocation , In addition, it has expanded a namedtuple
function , Finally, you can expand on timeit
modular .