Three differences between python tuples and lists

Three differences between tuples and lists

There are many similarities between python's tuples and lists, such as iterable iterable objects, they are ordered, they can be accessed and sliced ​​​​by indexing, and so on. As different data structures, python's tuples and lists also have their differences. Here are just three of them , as follows:

  1. Lists can be reassigned by index, but tuples cannot. If you try to reassign by index of tuple, python will throw a TypeError;
  2. Python lists are wrapped with "[]", while tuples are wrapped with "()";
  3. If there is only one element, the tuple needs to add a "," after the element, but the list does not;

Example code of three differences between tuple and list

//索引赋值的区别
>>> lst = list(range(6))
>>> lst
[0, 1, 2, 3, 4, 5]
>>> tup = tuple(lst)
>>> tup
(0, 1, 2, 3, 4, 5)
>>> lst[0] = 5
>>> lst
[5, 1, 2, 3, 4, 5]
>>> tup[0]=6
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
//只要一个元素时的区别
>>> type([1])
<class 'list'>
>>> type((2))
<class 'int'>
>>> type((3,))
<class 'tuple'>

Original: Three differences between python tuples and lists

Guess you like

Origin blog.csdn.net/weixin_47378963/article/details/130279563