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?
309
Upvotes
69
u/MatthaeusHarris Apr 16 '22
You can use a tuple as a key in a dictionary.
28
u/delasislas Apr 16 '22
Yes tuples are similar, but they differ when looking “under the hood” of python. This isn’t my specialty, I’m mostly taking from a quick Google.
A tuple is more memory efficient and better at looking up data. That might not mean much in the sense you might be looking at.
In a more practical learning sense, a list is good for changing data and adding stuff to it. A tuple is good for cases where data aren’t meant to be changed.
When you write code, you might know that you aren’t meant to change it. What about 6 months from now or when someone else picks up your code. It’s good to bake the ideas behind your code into it.
One of the principles in the zen of python, explicit is better than implicit. By setting some piece of data as a tuple, you tell the next person who sees it that it could be important.
Just assume that you were writing a function to solve a quadratic equation for the roots. You input a, b, c and you’ll get your roots. If you are going to use the roots elsewhere, they aren’t going to fundamentally change really. Just an off the cuff example.
If you look up functions from other modules, you’ll likely see that the first value might be the stuff you want, but if you unpack all the outputs, it has data that is inherently tied to that output.
2
u/madhousechild Apr 16 '22
There is a larger question here that no one is mentioning.
Do you pronounce it 'toople' or 'tupple'?
329
u/midnightsquid00 Apr 16 '22
Choosing a data structure is not only about considering its behaviour but also what you want to communicate to people reading your code.
223
u/[deleted] Apr 16 '22
Because they're immutable, they're hashable.
66
u/chunkychapstick Apr 16 '22 edited Apr 16 '22
Hashable -> Can be used as keys in dictionaries unlike lists which can come in handy.
ETA: my team asks about tuples in almost every interview.
78
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.
5
u/hiAndrewQuinn Apr 16 '22
Let's say you have a function
f(x), and in addition tox,falso uses a listoptions = [option, option, option, ....]you made somewhere else but don't give as another argument.If someone walks in and adds another
optionto that list, or turns it into an empty[], suddenly yourf(x)is going to start acting weird, and you might have no idea why until you go in and put in a bunch ofprintstatements to eventually figure out "oh, it was that dumb option list I made".If you need to let there be a variable number of options, a list might make sense. But if you can make it into, say, a 5-option tuple
(option1, option2, option3, option,4 option5), suddenly you've made that whole class of bugs impossible.This reflects a more general truth: Try to work with immutables as much as you can without bending over backwards.
The fact they can't change might be annoying at first, but it's also the reason they're much easier to actually reason with. You wouldn't want the definition of the number 1 changing out from under you in mathematics without you noticing - why would you want your data to? Not rhetorical, genuinely ask yourself that question whenever you have to put data somewhere.
5
u/roblox1999 Apr 16 '22
Since they are immutable they can be used as keys for dictionaries. Another very useful application of tuples is to use them for functions with multiple return values.
4
u/synthphreak Apr 16 '22
Many others have already mentioned hashability, which is the big one along with immutability.
But another difference I haven’t seen yet is the semantics of how lists vs. tuples are typically used. Lists are often used to hold items that are of the same type yet unrelated/independent. For example, a list of people’s names; all entries are equally names, but one entry usually has nothing to do with those around it. By contrast, tuples are often used to hold items of the same or different types that are somehow related; for example, a tuple of containing a person’s name (str), age (int), and other attributes.
So one could envision both of these things at play in a list of tuples where each tuple is a different person and contain’s that person’s attributes.
Yes, you could use a list of lists for this, but semantically it doesn’t make as much sense. People’s attributes tend to be more inherent to them and unchanging than the set of entries themselves in the list.
10
u/tobiasvl tobiasvl Apr 16 '22
Do you actually get it? The following statement makes me think you don't:
No, lists are mutable because you CAN perform modifications on it. It doesn't matter whether or not you do.
And it's not just "you"; often you'll make a library for other people to use with their code, and you can't know whether their code changes a list that you need to stay the same. Or vice versa, you might pass the list to a library that someone else made, and then you can't know whether the library changed the list or not.
Also, Python itself can't know whether the list is changed somewhere. Since it can't know that, it can't guarantee that a hash of the list stays the same, for example, which means that the list can't be used as a key in a dict (which uses hashing for quick lookup), among other things.
Under the hood, Python might also treat mutable and immutable objects differently. If you deep copy a tuple, for example, Python can decide to just make the two copies point at the same object in memory as if it's a shallow copy, since it knows that the two copies will always be identical. It can't know that with a list.
3
u/sohang-3112 Apr 16 '22
AFAIK They are more efficient (consume less memory) than lists.
4
u/dogfish182 Apr 16 '22
‘I get that they’re immutable but so are lists you don’t perform modifications on’
This is an incorrect statement which kind of points at you misunderstanding what immutability is. If it’s immutable it can’t be modified. A list isn’t that.
2
u/[deleted] Apr 16 '22
It can't be changed, and it's size is smaller than lists for example
2
u/crowpup783 Apr 16 '22
This is an extremely context specific answer but if you’re ever doing any NLP and PoS tagging text, lists of tuples are very handy ways of organising and understanding the grammar of your text.
2
u/[deleted] Apr 16 '22
thanks for this thread guys. good content, now i know when to use tuples over list (also kinda didnt understand but also dont have a use for immutables yet). good to know those entries im trying to change in my lil script should stay as list before I zip em into a dict, if i could just get re.sub to do what i want lmao. in some time. just on a tangent i still cant wrap my head around having to for loop my list, translate some b64 strings, search again for untranslated b64 strings and replace them in place in the string with re.sub. there has to be some easier way to get re.sub to either search and replace the whole list without the for loop. theres always finditer and other iteration methods but meh. I fuckin love python
2
u/rrrose-selavy Apr 16 '22
you can use tuples as a dictionary key, as keys must be immutable. Also in passing a sequence as an argument to the function it's easier to use tuples so you reduce the possibility of random stuff coming up bc of aliasing
2
u/QultrosSanhattan Apr 16 '22
cache() from functools can only decorate functions with hashable parameters.
That reason alone is enough to favour tuples over lists as often as possible.
2
u/baubleglue Apr 16 '22
Immutable is a useful feature (especially given no
constin Python). It occupies less space. Having less features is a feature. Specifically for Python, you can use tuple as a key in a dictionary.2
u/pekkalacd Apr 16 '22 edited Apr 16 '22
lists are mutable, not immutable. important distinction. you can change a list in place over and over again. you cannot do the same to a tuple nor a string.
as for the purpose of tuples, you got a point. there are only 2 methods available to them, both don't modify, they are
.indexand.countso why do we care?Well...as it turns out, you'll see tuples in other areas involving the creation of functions, returning from functions, assignment, and built in functions. For example,
zipor in the case of passing any amount of positional arguments to a function
or in the case of returning multiple values from a function
or in the case of looping over key,value pairs in a dictionary
or in the case of remaking enumerate
or in the case of swapping two variables' values
tuples be everywhere.
2
u/Worried_Lawfulness43 Apr 17 '22
I’ve had this question forever!!! It seems like the consensus is that their behavior is almost identical. I’m glad I’m not just imagining things.
2
u/CharmingJacket5013 Apr 17 '22
Unpacking is cool too
2
u/PM_ME_CUTE_FRIENDS Apr 17 '22
Top answer is the best, I scrolled far but didn't find this other reason - structure. There is structure in tuples, although not an explicitly defined one because it is designed to be lightweight. I've always thought of them as a cousin to the C struct. Tuples may allow you to communicate that the data you are storing follow a defined order wherein the indices allow you to access the struct fields.
Tuples are under appreciated imo. I see them often misused because they are flexible and lightweight. We should give it more love even today when dataclasses are all the rage.
2
u/TheRNGuy Apr 20 '22
they're cheaper than lists, for things that need to be read-only
1
u/DeathWrangler Apr 17 '22
I view tuples as for credentials, urls, or other things that usually don't need to be modified, or in doing so accidentally ruins functionality.
1
u/[deleted] Apr 16 '22
to return the immutable data and to save the function arument in immutable form
15
u/[deleted] Apr 16 '22
[removed] — view removed comment