When to use lists and when to use tuples?

Asked

Viewed 10,500 times

7

What’s the difference between the types list and tuple in Python and when to use each?

1 answer

14


Both are types of data sequences, but one is mutable and the other immutable. Both list and tuple are data sequences and have many common properties, but the basic difference is that the list is mutable and the tuple is immutable.

What is immutable?

According to the glossary from the Python language documentation, immutable refers to an object with a fixed value. Immutable objects include strings, numbers, and tuples. If it is necessary to change the value of an immutable object, another object must be created in order to store it. They play an important role in places where a value of hash constant is needed, for example as a key in a dictionary.

In practice, this implies that it is not possible to make assignments to an immutable object. For a list, as the example below, it is possible to change it through an assignment operation:

>>> lista = [0, 1, 2, 3]
>>> print(lista)
[0, 1, 2, 3]
>>> lista[0] = 9
>>> print(lista)
[9, 1, 2, 3]

However, repeat the example using a tuple:

>>> tupla = (0, 1, 2, 3)
>>> print(tupla)
(0, 1, 2, 3)
>>> tupla[0] = 9
TypeError: 'tuple' object does not support item assignment

An error is triggered when attempting to assign an object of the tuple type.

Common list and tuple operations

The operations listed below work for s and t being both lists and tuples.

Operações comuns às sequências Source: Built-In Types: Common Sequence Operations

And what’s the difference?

The only operation that immutable types implement that mutable types do not support is the function hash(). This allows immutable types, such as the tuple, to be used as dictionary keys and stored in set and frozenset.

So it’s possible to do:

>>> d = {
...     (1, 2): "Stack Overflow em Português"
... }
>>> print(d)
{(1, 2): 'Stack Overflow em Português'}

For, in memory, the key of the dictionary is related to the value hash tuple. Being a list a changeable type, doing the same results in an error indicating that the list does not support hash.

>>> d = {
...     [1, 2]: "Stack Overflow em Português"
... }
TypeError: unhashable type: 'list'

Care

Although the tuple is an immutable type, if it has a value of a mutable type, it remains mutable while inside the tuple. For example, if we consider a list tuple:

>>> tupla = ([1, 2], [3, 4])

You can change the list values:

>>> tupla[0][0] = 9
>>> print(tupla)
([9, 2], [3, 4])

Or even call the native methods the object type, such as append:

>>> tupla[1].append(0)
>>> print(tupla)
([9, 2], [3, 4, 0)

Although this is possible, the object, even of the tuple type, loses the property of being an immutable type and therefore ceases to be an object hashable. When trying to do, considering tupla of the previous example:

>>> hash(tupla)
TypeError: unhashable type: 'list'

An error will be triggered indicating that the tuple has values that are mutable and therefore impossible to calculate the hash.

When lists are used?

The lists are mutable sequences, typically used to store collections of homogeneous items (where the precise degree of similarity will vary according to the application).

That is, if a list contains integer values, it is expected to be only integers. You will hardly have a list storing values of different types, such as [1, "Foo", True].

Source: Built-In Types: Lists

When tuples are used?

Tuples are immutable sequences, normally used to store heterogeneous data collections (such as the tuple produced by the function enumerate native). Tuples are also used for cases where an immutable sequence of homogeneous data is required (such as allowing storage in set or dict).

Tuples can have values of different types, where each one represents something specific. As the return of the function itself enumerate of a list, the return will be a tuple of two values, in which the first represents the index of the value in the list and the second the value itself.

>>> lista = ["a", "b", "c"]
>>> print(list(enumerate(lista)))
[(0, 'a'), (1, 'b'), (2, 'c')]

That is, one value of the tuple is of the integer type, while the other is of the string type.

Source: Built-In Types: Tuples

Named tuples

If you still want to use the properties of the tuple, but want to access its values through named indexes, you can use the structure collections.namedtuple.

>>> import collections
>>> Person = collections.namedtuple('Person', 'name age gender')
>>> foo = Person(name="Foo", age=30, gender="male")
>>> print(foo)
Person(name='Foo', age=30, gender='male')
>>> print(hash(foo))
2739343292757077799

Note that even if a tuple is named, use the function hash is still possible (provided the values are all of immutable types).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.