r/learnpython • u/Pure-Homework681 • Mar 27 '23
Actually using a tuple
Can someone, please, give me a "real-world" example on the use of a tuple? I'm learning through w3schools. The idea of a tuple sort of makes sense, but I have no idea how it would/could be applied.
147
Upvotes
8
u/POGtastic itertools evangelist Mar 27 '23
Semantically, tuples contain heterogeneous data. They are the simplest product type.
I expect that every element of a list be the same type. I can have a list of integers, or a list of strings, or a list of dictionaries, or whatever. I should not have a list where each element could either be an integer or a string.
By contrast, I expect that the first element of a tuple could be different from the second element of a tuple! For example, the
enumeratebuiltin zips an iterable with integers. The type of the second element of each tuple is different from the type of the first element!Everything else (tuples being immutable, hashable, and slightly more performant than lists) is a neat implementation detail. The far more important purpose of the tuple being distinct from a list is that it represents a mathematical idea of a tuple.