list(Recommended learning: web front-end video tutorial)
1. The list is An ordered collection in which elements can be added and deleted at any time
2. When accessing elements in the list, the index starts from 0, and 0 is the first element. When the index exceeds the range, an error will be reported, and the index cannot Out of bounds, the index of the last element is len(num)-1
3. If you want to get the last element, in addition to calculating the index position, you can also use -1 as the index to directly get the last element
4. Use append() to add elements to the end of the list.
5. Use insert() to insert elements into the specified position.
6. Use pop() to delete them. The last element of the list; Use pop(i) where i is the index number to delete the element at the specified position
tuple
1. Tuple is an ordered list , it is very similar to list
2. Once the tuple is initialized, it cannot be modified, and there are no methods such as append() insert(). Elements can be obtained but cannot be assigned to another element
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)
list is a variable data type, tuple is an immutable data type
type uses (), list uses []
in Use lists when you have some queues of the same type of indefinite length; use tuples when you know the number of elements in advance, because the position of the elements is important.
Lists cannot be used as dictionary keys, but tuples can
*Both tuples and lists can be nested, and tuples can Nested lists within groups are mutable
What is the point of immutable tuples?
Because tuples are immutable, the code is safer. If possible, use tuple instead of list.
The above is the detailed content of The difference between tuple and list in python. For more information, please follow other related articles on the PHP Chinese website!