Here I want to talk about list and tuple in Python. In fact, according to the semantics, we also know that list and tuple refer to the list. Next, I will directly introduce the usage and difference between list and tuple in detail with a table.
usage | list | tuple |
---|---|---|
ordered list | ordered list | |
definition | Built-in sorted collection, mutable | Built-in sorted collection, immutable |
application | classmates= [‘Michael’,’Ada’,’Kitty’] | classmates = (‘Michael’,’Ada’,’Kitty’) |
number of elements | len(classmates) | 234 |
find element | The first one: classmates[0] | The last one: classmates[-1] |
insert element | classmates.insert(1,’Amy’) | without |
Additional elements | classmates.append(‘Amy’) | without |
delete the specified element | classmates.pop(1) | without |
remove the last element | classmates.pop() | without |
replace element | classmates[0] = ‘Sarah’ | without |
Data types can be different | classmates = [‘Ada’, 123, wo] or classmates = [‘Ada’, [‘Amy’, ‘cool’], 123] | t = ('Ada', ['Amy', 'cool'], 123) ————– At this time, there is a list in the tuple, and the list is variable |
empty list | classmates = [] len(classmates) 为0 | classmates = () |
only one element | classmates = [0] | classmates = (1,) to disambiguate |