List
Ordered
Tuple:
Another ordered list is called a tuple: a tuple. Tuple and list are very similar, but a tuple cannot be modified once initialized
Dict
Disordered
Contrast:
Compared with list, Dict has the following features:
- The speed of finding and inserting is very fast and will not slow with the increase of key;
- It takes a lot of memory, and it wastes a lot of memory.
And the list is the opposite:
- The time to find and insert increases as the element increases;
- Small footprint and little wasted memory.
So, Dict is a way of exchanging space for time.
Dict can be used in many places where high-speed lookups are needed, almost everywhere in Python code, it is important to use dict correctly, and the first thing to keep in mind is that the Dict key must be an immutable object .
This is because Dict calculates the storage location of value based on key, and if each calculation of the same key results in a different result, the dict interior is completely chaotic. The algorithm for calculating the position by key is called the hash Algorithm (hash).
To ensure the correctness of the hash, the object as a key can not be changed. In Python, strings, integers, and so on are immutable, so you can safely use them as keys. The list is mutable and cannot be a key:
Set
Set is similar to Dict and is a set of keys, but does not store value. Because key cannot be duplicated, there is no duplicate key in set. unordered .
Re-discussing non-mutable objects
' ABC '>>> b = a.replace ('a'a')> >> b'abc'>>> a'ABC '
Always keep in mind that a
it is a variable, but a ‘abc‘
string Object! Sometimes, we often say that the object's a
content is ‘abc‘
, but actually refers to, a
itself is a variable, it points to the content of the object is ‘abc‘
:
When we call a.replace(‘a‘, ‘A‘)
, the actual invocation method replace
is on the string object ‘abc‘
, and although the method is called, it replace
does not change ‘abc‘
the contents of the string. Instead, the replace
method creates a new string ‘Abc‘
and returns, and if we point to the new string with a variable, b
it's easy to understand that the variable a
still points to the original string ‘abc‘
, but the variable points to the b
new string ‘Abc‘
:
Therefore, for an immutable object, any method that invokes the object itself does not change the contents of the object itself. Instead, these methods create a new object and return it, ensuring that the immutable object itself is always immutable.
Reprint: Https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/ 00143167793538255adf33371774853a0ef943280573f4d000
Python:dict vs List vs Set