What’s the difference between lists and tuples?

Technology CommunityCategory: PythonWhat’s the difference between lists and tuples?
VietMX Staff asked 3 years ago

The key difference is that tuples are immutable. This means that you cannot change the values in a tuple once you have created it. So if you’re going to need to change the values use a List.

Apart from tuples being immutable there is also a semantic distinction that should guide their usage. Tuples are heterogeneous data structures (i.e., their entries have different meanings), while lists are homogeneous sequences. Tuples have structure, lists have order.

One example of tuple be pairs of page and line number to reference locations in a book, e.g.:

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

You can then use this as a key in a dictionary to store notes on locations. A list on the other hand could be used to store multiple 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.