What’s the difference between lists and tuples?

Problem

What’s the difference?

What are the benefits and drawbacks of tuples and lists?

Solution #1

Apart from the fact that tuples are immutable, there is a semantic distinction that should be considered while using them. Lists are homogeneous sequences, but tuples are heterogeneous data structures (i.e., their entries have diverse meanings). Lists have order, while tuples have structure.

Using this distinction clarifies and simplifies the code.

Pairs of page and line numbers, for example, can be used to refer to specific areas in a book, such as:

``````my_location = (42, 11)  # page number, line number
``````

You may then use this as a key in a dictionary to keep track of where you’ve been. On the other hand, a list can be used to keep track of several locations. Naturally one might want to add or remove locations from the list, so it makes sense that lists are mutable. On the other hand it doesn’t make sense to add or remove items from an existing location – hence tuples are immutable.

When iterating through the lines of a page, there may be times when you want to update things within an existing location tuple. Tuple immutability, on the other hand, necessitates the creation of a new location tuple for each new value. This seems inconvenient on the face of it, but using immutable data like this is a cornerstone of value types and functional programming techniques, which can have substantial advantages.

“Python Tuples are Not Just Constant Lists” or “Understanding tuples vs. lists in Python” are two noteworthy papers on this topic. This is also mentioned in the official Python manual.

In a statically typed language like Haskell, a tuple’s values are usually of distinct types, and the tuple’s length must be fixed. The values in a list are all of the same type, and the length is not fixed. As a result, the distinction is clear.

Finally, Python has a namedtuple, which makes sense because a tuple is supposed to have structure. Tuples are a lightweight alternative to classes and instances, as evidenced by this.

Solution #2

What is the difference between a list and a tuple?

Solution #3

If you went on a walk, you could keep track of your coordinates in a (x,y) tuple at any time.

If you wanted to keep track of your journey, you could add your location to a list every few seconds.

However, you wouldn’t be able to do it the other way around.

Solution #4

Tuples are distinct in that they are immutable. This means that after you’ve generated a tuple, you can’t change its values.

If you’re going to need to alter the values, a List is the way to go.

Benefits to tuples: