When to use lists and when to use tuples? [duplicate]

5

What is the difference between list and tuple types in Python and when should I use each one?

    
asked by anonymous 26.03.2017 / 01:27

1 answer

10

Both are types of data sequences, but one is changeable 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 changeable and the tuple is immutable.

What is immutable?

According to the glossary of the Python language documentation, immutable refers to an object with fixed value. Unchanging objects include strings, numbers, and tuples. If you need 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 constant hash value is required, 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, like the example below, you can 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 trying to make an assignment to an object of type tuple.

Common list operations and tuples

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

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 hash() . This allows immutable types, such as tuple, to be used as dictionary keys and stored in set and frozenset .

So you can do:

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

Because in memory, the dictionary key is related to the hash value of the tuple. Being a list a changeable type, doing the same results in an error stating 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 changeable 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 values in the list:

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

Or even call native methods of 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 thus ceases to be a hashable object. 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 compute the hash .

When using lists?

Lists are changeable, typically sequences used to store collections of homogeneous items (where the precise degree of similarity will vary by application).

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

Source: Built-In Types: Lists

When using tuples?

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

Tuplets can have values of different types, where each one represents something specific. As the return of the enumerate function of a list, the return will be a tuple of two values, where 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 tuple value is integer type, while the other is string type.

Source: Built-In Types: Tuples

Named tuples

If you still want to use tuple properties, but want to access their 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 though it is a named tuple, using the hash function is still possible (as long as the values are all of immutable types).

    
26.03.2017 / 06:30