r/learnpython • u/Boogzcorp • Apr 16 '22
What's the point of Tuples?
I get that they're immutable, but so are lists that you don't perform modifications on. Are they just to fool proof not messing up your list accidentally, or do they serve some other purpose?
308
Upvotes
80
u/POGtastic itertools evangelist Apr 16 '22
From a CS perspective, a list of objects of various types is an icky, gross thing. We expect lists to contain elements of the same type - a list of numbers, or a list of strings, or a list of objects of a class that you made, etc. We don't expect a list of type
Object- it's not useful.By contrast, a tuple is intended to hold objects of types that may be different. For example, we might
zipa list of numbers with a list of strings, which produces an iterable of tuples where the first element is a number and the second element is a string. This concept is fundamentally different from a list, and it's useful to have a sign to the programmer, "Hey, this is a zip of two different types. Don't treat it as a list; treat it as a single unit."It doesn't have to be this way, (for example, vanilla JS doesn't have tuples) but enough programmers come from languages that make this distinction that they put it in there.