# lists - tuple python 3

## Python: what is the difference between(1,2,3) and[1,2,3], and when should I use each? (4)

In many places, `(1,2,3)` and `[1,2,3]` can be used interchangeably.

When should I use one or the other, and why?

Because of their immutable nature, tuples (unlike lists) are hashable. This is what allows tuples to be keys in dictionaries and also members of sets. Strictly speaking it is their hashability, not their immutability that counts.

So in addition to the dictionary key answer already given, a couple of other things that will work for tuples but not lists are:

``````>>> hash((1, 2))
3713081631934410656

>>> set([(1, 2), (2, 3, 4), (1, 2)])
set([(1, 2), (2, 3, 4)])``````

From the Python FAQ:

Lists and tuples, while similar in many respects, are generally used in fundamentally different ways. Tuples can be thought of as being similar to Pascal records or C structs; they're small collections of related data which may be of different types which are operated on as a group. For example, a Cartesian coordinate is appropriately represented as a tuple of two or three numbers.

Lists, on the other hand, are more like arrays in other languages. They tend to hold a varying number of objects all of which have the same type and which are operated on one-by-one.

Generally by convention you wouldn't choose a list or a tuple just based on its (im)mutability. You would choose a tuple for small collections of completely different pieces of data in which a full-blown class would be too heavyweight, and a list for collections of any reasonable size where you have a homogeneous set of data.

The list [1,2,3] is dynamic and flexible but that flexibility comes at a speed cost.

The tuple (1,2,3) is fixed (immutable) and therefore faster.

Tuples are a quick\flexible way to create composite data-types. Lists are containers for, well, lists of objects.

For example, you would use a List to store a list of student details in a class.

Each student detail in that list may be a 3-tuple containing their roll number, name and test score.

`` `[(1,'Mark',86),(2,'John',34)...]```

Also, because tuples are immutable they can be used as keys in dictionaries.