The difference between tuple and list in python

(*-*)浩
Release: 2019-09-02 11:24:31
Original
7078 people have browsed it

The difference between tuple and list in python

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)
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template