Especially when encountering similar data types like tuple and list, you may just think of tuple as const list. Yes, tuple is immutable (cannot be changed), and list is mutable (can be changed). , the rest seem to be similar, so why is there any need for tuple to exist?
list and tuple are both sequence type container objects, which can store any type of data and support slicing, iteration and other operations (recommended learning: Python video tutorial)
foos = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] foos[0:10:2] [0, 2, 4, 6, 8] bars = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9) bars[1:10:2] (1, 3, 5, 7, 9)
Difference:
The most fundamental difference is that list is a variable data type and tuple is an immutable data type
List uses [], tuple uses ().
tuple does not have insert, pop, append methods
Because tuple is immutable, the code is safer. If possible, use tuple instead of list.
In development use:
Use lists when you have some queues of the same type with uncertain lengths; use elements when you know the number of elements in advance Group because the position of the elements is important.
Lists cannot be used as dictionary keywords, but tuples can
*Both tuples and lists can be nested, and nested lists in tuples are variable
For more Python related technical articles, please visit the Python Tutorial column to learn!
The above is the detailed content of The difference between python list and tuple. For more information, please follow other related articles on the PHP Chinese website!