In Python, when should you use lists and when tuples?
Sometimes you don't have a choice, for example if you have
"hello %s you are %s years old" % x
then x must be a tuple.
But if I am the one who designs the API and gets to choose the data types, then what are the guidelines?
Tuples are fixed size in nature whereas lists are dynamic.
In other words, a tuple
is immutable whereas a list
is mutable.
in
operator to check if an element exists in the tuple.Tuples are faster than lists. If you're defining a constant set of values and all you're ever going to do with it is iterate through it, use a tuple instead of a list.
It makes your code safer if you “write-protect” data that does not need to be changed. Using a tuple instead of a list is like having an implied assert statement that this data is constant, and that special thought (and a specific function) is required to override that.
Some tuples can be used as dictionary keys (specifically, tuples that contain immutable values like strings, numbers, and other tuples). Lists can never be used as dictionary keys, because lists are not immutable.
Source: Dive into Python 3