current position：Home>Python lists and tuples
Python lists and tuples
2022-02-02 12:26:03 【asd3331380】
from ： Micro reading （www.weidianyuedu.com） Micro reading - Complete collection of model articles - Free learning website
One 、 The difference between lists and tuples
A list is a dynamic array , They are immutable and can be reset in length （ Change the number of internal elements ）.
Tuples are static arrays , They are immutable , And its internal data cannot be changed once it is created .
Tuples are cached in Python Runtime environment , This means that every time we use tuples, we don't need to access the kernel to allocate memory .
These differences are different in design philosophy ：
Lists can be used to hold data sets of multiple independent objects
Tuples are used to describe multiple attributes of a transaction that will not change
Two 、 list （List）
Once the list is created, we can change its content according to our own needs ：
>>> l = [1, 2, 3, 4, 5, 6]>>> l = l * l>>> l[12, 2, 3, 4, 5, 6]
In addition, we can add new data to the column edge to increase its size ：
>>> len(l)6>>> l.append(7)>>> l[12, 2, 3, 4, 5, 6, 7]>>> len(l)7
This is because dynamic arrays support resize operation , You can increase the capacity of the array . When a size is N The first time you need to add data to your list ,Python A new list will be created , Enough for the original N Elements and additional elements . however , What is actually allocated is not N+1 Elements , It is M Elements ,M > N, This is to make room for future . Then the data from the old list is copied to the new list , The old list will be destroyed . In terms of design concept , The first addition may be the beginning of many subsequent additions , By reserving space , We can reduce the number of operations to allocate space and the number of memory copies . This is very important , Because memory replication can be very expensive , Especially when the list size starts to grow .
3、 ... and 、 Tuples （Tuple）
Tuples are fixed and immutable . This means that once tuples are created , Unlike the list , Its content cannot be modified or its size cannot be changed .
>>> t = (1, 2, 3, 4)>>> t = 5Traceback (most recent call last): File "<stdin>", line 1, in <module>TypeError: 'tuple' object does not support item assignment
Although they do not support resizing , But we can combine two elements into a new element group . This operation is similar to that of a list resize operation , But we don't need to allocate any extra space for the new tuples ：
>>> t1 = (1, 2, 3, 4)>>> t2 = (5, 6, 7, 8)>>> t1 + t2(1, 2, 3, 4, 5, 6, 7, 8)
If we compare it to the... Of the list append Operation comparison , We will see that its complexity is O(n) Instead of listing O(1). This is because every new element added to a tuple will have allocation and copy operations , Instead of just happening when the extra space runs out like a list . So tuples don't provide a similar append Self - increment operation , Adding any two tuples always returns a newly allocated tuple .
The website is Python Tutor, One can be right python Run memory visualization website , Very suitable for beginners to study , What happens to memory during operation .
Another benefit of the static nature of tuples is that some will Python What happened backstage ： Resource cache .
Python It's a garbage collection language , This means that when a variable is no longer used ,Python The memory used by this variable will be released back to the operating system , For other procedures （ Variable ） Use . However , For length is 1~20 tuples , Even if they're not in use , Their space is not immediately returned to the system , It's reserved for future use . This means that when a new tuple of the same size is needed in the future , We no longer need to request a piece of memory from the operating system to store data , Because we've got space for that .
This may seem like a subtle benefit , But it's actually a magical place ： They can be created easily and quickly , Because they can avoid frequent contact with the operating system , The latter will take a long time .
The following example will be very intuitive to illustrate the problem
In : %timeit l = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]93.7 ns ± 3.33 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)In : %timeit t = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)18.5 ns ± 1.19 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
The above example shows that initializing a list is slower than initializing a tuple 5.1 times —— If this is in a loop , This difference will quickly add up .
author[asd3331380],Please bring the original link to reprint, thank you.
The sidebar is recommended
- 【Python】2. Logic control statement, list, tuple, dictionary
- Write an Enigma machine in Python
- Python lists, dictionaries, tuples, collections, learning notes
- Python actual combat case, requests module, python implementation, obtaining dynamic charts
- Information recommendation platform based on Python search engine and recommendation algorithm
- It's better to know the python decorator than to know the heart of your girlfriend
- Use Python to develop a dinosaur running game and play it
- Use SciPy FFT for Fourier transform: Python signal processing
- Let the python program automatically play Sudoku, and the second becomes the strongest brain!
- Python ETL tool
guess what you like
Vue3 + ant design Vue + Python realizes the combined deployment of a set of code and multiple sub applications
Python snail sorting
Generating AI web applications using Python and flask
Share 4 practical Python automation scripts
[Python basics] Python collaboration
11 "Python dictionary" knowledge points easy to use
These 20 pandas functions can improve your 'data cleaning' ability by 100 times
British one-to-one student Python poker homework Q & A
Django's 35000 word blog post
Four skills of pandas row column conversion
- Python actual combat case, mplcyberpunk module, python realizes cyberpunk data visualization
- What are the differences between golang and python 3?
- Detailed explanation of Python + fidder 4 web crawler (the most complete in Station C)
- Pycham operation and configuration guide can't do this. It must be slow to write python
- "Top level introduction to Python" is the devil's step step by step
- Summary of the most complete Python Library in Station C - standard library + advanced library (10000 word long text, recommended Collection)
- Python realizes GIF dynamic drawing and video card communication, kicks two feet to break the dimensional wall | machine learning
- Python realizes the cartoon of photos and breaks the dimensional wall with one punch | machine learning
- Python to achieve picture beautification, drunk do not know the sky in the water? (attach code) | machine learning
- Python projects are packaged into executable exe files
- Python video conversion resolution (with code) | Python tool
- Python modify picture resolution (with code) | Python tool
- Python file upload Minio and Ali OSS tools | Python tools
- Python video add audio (with code) | Python tool
- Python game development, python to achieve Snake games and eat beans with source code
- What language is Python
- [untitled] Python magic method__ new__ method
- Use Python to get the information of popular positions and see what skills you need from a high salary
- Notes on Python deep learning (11): loss function
- Python foundation 2.4 -- tuple
- Case 58 of 120 Python crawlers, mobile app crawler, preparation of "arsenal" and test of skin shrimp app
- Asynchronous programming in Python
- Python -- concave polygon boundary extraction of plane point cloud
- Python learning (4)
- How to solve the problem of customization? (Language Python)
- Asynchronous programming in Python
- Python crawler programming analysis and cases Chapter 1 mitmproxy + Python crawler programming
- Python tiktok programming analysis and case mitmproxy + python+Appium grab shake fan information
- Analysis of Python crawler programming and installation of mitmproxy
- Programming with Python and C language
- PIP installation pypesq reported an error python3 seven
- It took three months, the most detailed and complete, 402 pages of Python learning materials. You'll lose money if you don't read it
- The accuracy of Python naive Bayes is too low
- Have you learned the common English vocabulary of Python?
- Python 32bit desert plug-in registration
- A popular but very easy-to-use built-in function in Python
- Introduction to Python testing framework pytest
- Recommended 4 books for Python
- Three ways of generating Excel files with Python
- Python training artificial intelligence 7