What is the main difference between a Tuple and a List?


What are the differences between Tuple and List in Python ?


>a = [1, 2, 3] 
# [1, 2, 3]
>b = (1, 2, 3)
# (1, 2, 3)

The Tuple , grotesquely speaking, is a constant that accepts List ?

asked by anonymous 03.03.2015 / 16:12

2 answers


From a technical point of view in Python a tuple is immutable and a list is changeable.

From a conceptual point of view, you should use tuples to construct heterogeneous data structures while the list should be used for homogeneous data, ie all elements should be of the same type.

Since Python is a dynamic language this can not be guaranteed, it is up to the programmer to decide to do this.

Because it is used for heterogeneous data (diversity of types among members) the tuple usually has few elements but nothing prevents it from having many. Tuples are often used to simulate classes that do not need to be defined, whose use is more ephemeral and does not depend on more specific contracts.

But even if you have a list of elements that will usually be small, if it looks more like a list and not a limited set of data, the list should be used.

If the data is of the same type, you almost certainly do not have a list. Of course there are exceptions. For example a Point could be a tuple whose elements are two integers. Obviously this is not a list of data, but the limited set of data that happen to be of the same type.

The tuple works as a data record, such as a row in a database, a set of columns. The list works like the table, they are the lines as a whole.

I imagine, but I have never tested, that tuples are slightly faster, but they should not be used because of this.

03.03.2015 / 16:25

Complementing the response of the bigown user, the tuplas are immutable , therefore it is not possible to modify content without overwriting the variable a represents, whereas the list has several methods that change its structure.

When it is necessary to represent a structure that should not be modified, one must use tupla instead of lista , guaranteeing the integrity of the data and ensuring that until the programmer can not modify its structure. >

For example:

t = (1, 2, 3)
t = t + (4, 5)  # incremento de 2 elementos na tupla t, sobrescrita na variável t
l = [1, 2, 3]
l.extend([4,5])  # incremento de 2 elementos na lista l
13.09.2017 / 20:18