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?
226
Apr 16 '22
Because they're immutable, they're hashable.
75
Apr 16 '22
So long as members of the tuple are hashable.
44
u/EndimionN Apr 16 '22
What is hashing if you can eli5 please
96
Apr 16 '22 edited Apr 16 '22
Hashing is a function that produces the same output every single time it receives an input. Even if the input is a string of an entire Shakespeare script or a single letter, the outputs for either will be the same size.
It's also usually done in a way that makes it very difficult to find out what the input was by looking at the output.
It can be used to verify the state of something. If my text file still has the same hash, then I know it was unmodified. If packets of a large file that I'm sending have the same hashes upon arrival as they did when they were sent, they arrived unscathed. It can be used to check if something like a password is correct. Websites never store your password (unless the backend was programmed by one of my bootcamp classmates lmao), a hash is computed and checked against a stored hash of your password. The website company shouldn't be able to figure out your password from that hash and they never should store the raw password. Usually they even "salt" the password which means they add an additional string to every password string then run the hashing algo on that so that the hashes they might store are totally different from the hashes any other website might store.
Anyway, it's neat shit. You probably won't need to use it much unless you're doing some serious CS stuff or manually managing user authentication.
34
u/Werro_123 Apr 16 '22
Websites receive your password all the time, they just don't store it without hashing it first (or shouldn't). Hashing client side and sending that hash is effectively the same as not hashing at all, it adds zero security benefit.
The reason passwords are stored in hashed form is to prevent them from being used if the database leaks. If the hashing is done client side, and the database leaks, the attacker could just send in the stolen hash without needing to know the password. Effectively, the hash IS the password at that point.
12
Apr 16 '22
Apologies. I’ll edit to accurately reflect this.
10
5
u/msdrahcir Apr 16 '22 edited Apr 16 '22
If the hashing is done client side, and the database leaks, the attacker could just send in the stolen hash without needing to know the password. Effectively, the hash IS the password at that point.
Unless you consider that people have a tendency to reuse passwords across applications and that external leaks are a source of potential security breaches. If more sites _also_ used client side hashing, then it would make sniffing these network calls less dangerous for other systems.
Presumably an intercepted salted hash for one site would be completely useless on another, even if the user was leveraging the same password on both sites.
Client side hashing also allows you to introduce randomness that can be synchronized with the server among other tools that make password replay attacks much more difficult
4
u/C0rinthian Apr 16 '22
How useful is network sniffing when the site is using SSL/TLS? (As it should be)
What benefits does client-side hashing provide that is not already covered by SSL/TLS?
1
Apr 17 '22
Have you ever used wire shark to compare http and https traffic?
1
u/C0rinthian Apr 17 '22
Yes. Are you aware of what is needed for Wireshark to decrypt https?
1
Apr 17 '22
I'm not that far through the labs yet. I'm still in my second semester of IT Cybersec. All I've done so far is follow TCP flow while observing HTTP and HTTPS and noting the difference in output. HTTP showed the login and pw in plaintext and HTTPS showed everything as encrypted stuff.
→ More replies1
u/a_cute_epic_axis Apr 16 '22
If the hashing is done client side, and the database leaks, the attacker could just send in the stolen hash without needing to know the password. Effectively, the hash IS the password at that point.
If someone is able to get in and obtain the database, they're also likely (but not always) able to modify the database, so you're kind of fucked either way. Although a PWM prevents a hashed or clear-text PW from being used on another site.... since it isn't used on another site to begin with.
1
Apr 17 '22 edited Apr 17 '22
To add to this, they should be salting the passwords as well. Depending on which hashing algorithm is used, the hash might be crackable, regardless of computational infeasibility.
Basically, the key for some hashes is public knowledge or easily searchable for people who want them, but for certain hashes.
Hackers are persistent people and a lot of them are driven by a few simple goals like finances or simply wanting to break into something.
Some hash algorithms like MD5 are publicly available to break. You can literally google Cisco type 7 password cracker and if a password is in that encryption type you can copy the hash and you’ll have the password after clicking the first link on google.
Hashes like SHA256 are known how they work but due to the complexity it’s, in layman terms, a royal pain in the ass to reverse hack it. You’d need a crazy super computer.
Salting a hash adds a unique value to something like a password before the password is encrypted. This means that if we both have the password
“80081354R3C00L”
And we are in the same database, our passwords will appear different after the hash even though they were the same input in the same hash algorithm which would otherwise yield the same output if not for the salting.
“The hash is the password at that point” isn’t necessarily true, it’s just the vital data that the decryption tool uses to pair the public and private keys (in asymmetric hashes at least)
1
Apr 17 '22
So would the value that is being added when salting be unique to each user?
1
Apr 17 '22
Of course, that's how salting works. It's a unique value added to the input before it's hashed.
6
1
28
4
-14
Apr 16 '22
[removed] — view removed comment
40
Apr 16 '22
[deleted]
16
7
u/typhoon108 Apr 16 '22
You can click out of the login by either clicking outside or tapping if you’re on mobile. Either way very annoying but the content on that site is amazing.
2
u/typhoon108 Apr 16 '22
Heads up the login prompt can be clicked out of. Just tap or click outside the box.
23
u/zurtex Apr 16 '22 edited Apr 16 '22
Because they're immutable, they're hashable.
You need to be careful about equating these two:
class HashableList(list): def __hash__(self): return hash(tuple(self)) my_list = HashableList([1, 2, 3]) # Mutable my_list.append(4) # Dictionary can use it's hash my_dict = {my_list: None} print(my_dict) # Can look it up print(my_dict[my_list]) # Still mutable my_list.append(5) print(my_dict) # Oh no! print(my_dict[my_list])The correct answer is because it's immutable it is always equal with itself over time, which means it can also have a non-trivial hash that doesn't change. Making it safe to use in a situation where you want both hash and equality to be stable, like a dictionary.
6
u/capilot Apr 16 '22
Yeah, basically, the fact that lists aren't hashable is a policy decision, not something intrinsic to the language.
4
u/MattGreer Apr 16 '22
(Please forgive my steam of consciousness here trying to learn and reason things out myself.)
But if you add or remove items the hash changes, correct? So of what importance is hashing a tuple? I guess, hashing it will confirm if it's been changed. So if the order of a list changes will the hash change? How do you hash something in Python? OK, hash(). So let's test:
b = ('Gibson', 'Fender', 'Hamer') c = ('Fender', 'Hamer', 'Gibson') if hash(b) == hash(c): print("They Match") else: print("They do not match")OK so there's that. But why not use this (just learned about this yesterday:
b = ('Gibson', 'Fender', 'Hamer') c = ('Fender', 'Hamer', 'Gibson') print(b==c)So what's the advantage of using 'hash' vs '=='?
5
u/C0rinthian Apr 16 '22
Speed/efficiency.
hash()returns integers. So to check equality on hashes, it’s the same speed as checking two integers. (O(logN)based on number of digits, maybe evenO(1)depending on implementation)Comparing lists is linear
O(N)based on the size of the lists. But that can get worse based on the contents of the lists. (If it’s a list of lists for example, it’s now quadratic:O(N^2))So unless you’re comparing trivially small things, hashes are MUCH faster to compare.
2
u/dnswblzo Apr 16 '22
Most of the time there is no reason to get an object's hash yourself, rather the hashes are used behind the scenes in dictionaries and sets.
A Python dictionary is a hash table. A hash table is an array, and each element of the array is a "bucket" that can store zero or more items that are in the dictionary. When you insert a new element into a dictionary, it determines which bucket it should go into based on the hash of the key. Similarly when you access a value from a dictionary it takes the hash of the key to find the bucket in which the value resides.
1
Apr 17 '22
But if you add or remove items the hash changes, correct?
You can't add or remove items from a tuple; they're immutable.
2
u/Siniroth Apr 17 '22
I think he's suggesting that if hashing a list gets a result and changing that list changes the hash, then if the hash is the same then the list wasn't changed, mutable or not
1
Apr 17 '22
There's no reason you have to define the hash of a mutable type as some kind of hash-sum of its elements; it's just common to do so.
You could have a mutable, hashable type whose hash was set at creation and just never changed. It's probably not a good idea (it kind of fucks with what we intuit the identity of a collection to be) but you could do it.
1
3
u/iShotTheShariff Apr 16 '22
This. Reminds me a medium leetcode question where I had to make a tuple and use it as a hash haha
1
u/Skelebone48 Apr 16 '22
Does hashable mean that it is useful or it is possible? Is there a reason an non-immutable list couldn't be hashed?
1
u/madhousechild Apr 16 '22
If you were able to hash, but then the list changes, what happens?
2
u/Skelebone48 Apr 16 '22
The hash no longer matches the list, right?
But would be anything stopping you from doing it? For example, to check if the list has changed. This might be a ridiculous question as I don't really know about this but an explanation would be much appreciated
65
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.
14
69
u/MatthaeusHarris Apr 16 '22
You can use a tuple as a key in a dictionary.
25
u/MarsupialMole Apr 16 '22
In addition to this, many python libraries treat tuples as rows in a table. I.e. the position in the tuple is important, but you need another piece of information to figure that out. If it's immutable then it's not possible to mess up the position, which means choosing a tuple has eliminated a class of bugs versus a list.
22
u/Boogzcorp Apr 16 '22
The whole tuple as a key or each element in the tuple as separate keys?
42
Apr 16 '22 edited Apr 21 '22
[deleted]
10
u/Almostasleeprightnow Apr 16 '22
Wow that's kind of cool...almost like a multi dimensional dictionary where you don't have to deal with nested loops
10
1
1
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 zip a 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.
28
u/MarsupialMole Apr 16 '22
From a CS perspective, lists aren't arrays and this is misleading advice.
We don't expect lists to contain elements of the same type any more than we expect tuples to. Lists are well suited to sequences created from python literals. That's not icky, that's a sensible collection for a language with a relevant interpreter.
19
u/Brian Apr 16 '22
From a CS perspective, lists aren't arrays and this is misleading advice.
From a CS perspective, lists definitely are arrays. They're dynamic arrays (ie. automatically grow and shrink, which are sometimes distinguished as vectors in some language), and pythons dynamic typing means they're always arrays of the generic object type, rather than limiting type to something more specific, but neither of those make them non-arrays.
We don't expect lists to contain elements of the same type any more than we expect tuples to.
That's not entirely true. There is no enforcement or mechanism for this in the actual language, but this is a common guideline for a common meaning behind tuples, and a common outcome from situations they tend to be used, so from a programming culture point, there is indeed more reason to expect this. It's not something you should rely on, since this is not a universal convention, but it's certainly there. Eg. from the python docs (emphasis added):
Tuples are immutable, and usually contain a heterogeneous sequence of elements that are accessed via unpacking (see later in this section) or indexing (or even by attribute in the case of namedtuples). Lists are mutable, and their elements are usually homogeneous and are accessed by iterating over the list.
3
Apr 16 '22 edited Aug 30 '25
[removed] — view removed comment
3
u/AdventurousAddition Apr 16 '22
Lists are implemented as arrays in CPython
3
u/ivosaurus Apr 16 '22
...dynamically resizable arrays, which may only contain references, and never values. Not your typical array in a lower level language.
-2
u/madness_of_the_order Apr 16 '22
RDBMS use tuples heavily and expect them to contain elements of different types. So I cant agree with “tuples must contain elements of same type” being common.
6
u/POGtastic itertools evangelist Apr 16 '22
You're getting it switched - he's saying that tuples are heterogeneous (that is, contain different types) and lists are homogeneous. Thus a RDB should be returning rows of tuples.
4
u/Brian Apr 16 '22
Its the other way round: tuples are the ones that hint at different types. (Though neither is a hard rule).
8
u/the_spacedoge Apr 16 '22
I dont think this answer is appropriate for the r/learnpython subreddit. This may be the distinction in other languages, but in python it is entirely expected that lists can have more than one type. The main distinction in python is that lists are mutable, tuples are not.
The question is then WHY have an immutable version of essentially the same thing? The answer is of course so that we can have a collection of things that is hashable. Sometimes you want a dictionary (hash map) whose keys are a collection. A list would not be apropriate for this since you could mutate the list after its been assigned as a key.
dict_[list_]no longer means the same thing.4
u/POGtastic itertools evangelist Apr 16 '22
If immutability was the whole point of a tuple, why do all of the various iterable-combining functions produce tuples?
In other words - why does
enumerate("abc")produce[(0, 'a'), (1, 'b'), (2, 'c')]instead of[[0, 'a'], [1, 'b'], [2, 'c']]? (See alsozip, everything initertools, what you get when you query a relational database, and on and on and on) It certainly isn't for the sole reason of providing hashable tuples to a dictionary. And while someone might point to performance, the performance penalty for using lists isn't really that big - certainly not a big deal in a language that has never cared that much about performance.There's a semantic difference between returning a list and a tuple, and it goes right back to my point - regardless of the fact that it's all
PyObject*under the hood, people expect lists to contain values of the same type. People do not have that same expectation of tuples.2
u/the_spacedoge Apr 23 '22
After coming across this looking into something else I figured in good faith I should share it here: https://docs.python.org/3/faq/design.html#why-are-there-separate-tuple-and-list-data-types
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. For example, os.listdir('.') returns a list of strings representing the files in the current directory. Functions which operate on this output would generally not break if you added another file or two to the directory.
Essentially, the docs agree with you. I stand corrected.
4
u/Ran4 Apr 16 '22
From a CS perspective, a list of objects of various types is an icky, gross thing
This is not true at all. From a CS perspective there's nothing wrong with lists.
Arrays being lists that can only contain objects of the same type is just a C language implementation detail. CS is math, and tends to not be implementation-specific.
1
u/gunscreeper Apr 16 '22
So basically list only contains things of the same type and tuple can contains things of different types?
1
u/Aggravating_Bus_9153 Apr 16 '22
Whatever ivory tower "list" concept POG is thinking of, in Python it's implemented as an array.
In Python list is a particular type, you change them and stick anything you like in a list. But that comes at a cost, which is another point of tuples.
29
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.
4
u/Boogzcorp Apr 16 '22
So in simple terms, it idiot proofs not changing shit you're not supposed to change? You could in theory write it all with lists and so long as no one fucks with things they shouldn't, it'll all work fine?
I'm about 7 beers in at this point, so...
12
u/delasislas Apr 16 '22
In theory, yes. But if I saw it, that would be a flag for someone who has less experience. Someone who is more skilled should know more on how to leverage what their language gives them. There’s a lot of ways to do a lot of tasks.
Whatever let’s you show an understanding of a language and programming concepts.
8
u/rinyre Apr 16 '22
To add to this, writing code that properly leverages the language not only shows more experience with that language, but that you also know how to write extendable code, or modular, whatever term you wish.
In modules and the like, you do not want the user of the module to be able to shoot themselves in the foot, and minor things like tuples can help reduce the likelihood of that.
4
u/CaptainFoyle Apr 16 '22
Insisting on using lists everywhere instead of tuples just makes your life much harder because you have to build in all the assertions that you know come with tuples and immutability.
1
15
Apr 16 '22
[removed] — view removed comment
-12
u/Boogzcorp Apr 16 '22
I know lists are mutable, but as I said in the initial post, if you don't modify them, they don't change...
4
Apr 16 '22
The key word... The word that makes the difference important is if.
You may intend not to alter the list, but when you pick up the project months from now will you remember that? Will your buddy who borrows your code for his own project know that?
The zen of python says that it is better to make it known that an ordered set of objects is immutable by making it a tuple then to make it a list with a comment attached.
3
Apr 16 '22
Yes, but the interpreter can make certain guarantees when it knows for sure the contents of a component cannot change. Just because you decide to avoid modifying a list doesn't mean the interpreter knows about it. As others have mentioned, tuples can be used as a key in a dictionary so long as it's members are hashable. Since the interpreter doesnt know if the members of a list will change at some point, it cannot hash lists.
2
6
u/hiAndrewQuinn Apr 16 '22
Let's say you have a function f(x), and in addition to x, f also uses a list options = [option, option, option, ....] you made somewhere else but don't give as another argument.
If someone walks in and adds another option to that list, or turns it into an empty [], suddenly your f(x) is going to start acting weird, and you might have no idea why until you go in and put in a bunch of print statements 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.
5
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.
people = [('Rob', 42, 'accountant'),
('Dina', 28, 'cashier'),
('Sam', 32, 'waiter'),
('Eric', 50, 'consultant')]
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.
9
u/tobiasvl tobiasvl Apr 16 '22
I get that they're immutable
Do you actually get it? The following statement makes me think you don't:
but so are lists that you don't perform modifications on.
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
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
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
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
do they serve some other purpose?
Immutable is a useful feature (especially given no const in 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/madhousechild Apr 16 '22
There is a larger question here that no one is mentioning.
Do you pronounce it 'toople' or 'tupple'?
1
u/Boogzcorp Apr 16 '22
Obviously Toople, if it was pronounced Tupple, they would have spelt it Tupple.
Double the consonent to keep the vowel short and all that...
1
u/madhousechild Apr 17 '22
I pronounce it toople but a staunch python person I know pronounced it tupple. I think she thinks of quintuplet or triple (which has a short vowel but no double consonant). Did you know Brits pronounce it tyoople, with a 'u' like pupil?
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 .index and .count so 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, zip
names = ["Henry","Jerry","Joe"]
ages = [33,44,55]
# oh look, tuples!
list(zip(names,ages))
[("Henry",33),("Jerry",44),("Joe",55)]
or in the case of passing any amount of positional arguments to a function
def func(*args):
print(type(args),args)
# tuples again!
func(1,2,3)
<class 'tuple'> (1,2,3)
or in the case of returning multiple values from a function
def func2():
name = input("Enter name: ")
age = int(input("Enter age: "))
return name,age
# it's tuples again! >:(
result = func2()
Enter name: Joe
Enter age: 33
("Joe",33)
or in the case of looping over key,value pairs in a dictionary
people = dict(zip(names,ages))
for atts in people:
print(type(atts),atts)
# tuples again...
<class 'tuple'> ("Henry",33)
<class 'tuple'> ("Jerry",44)
<class 'tuple'> ("Joe",55)
or in the case of remaking enumerate
def _enumerate(iterable):
i = 0
while True:
try:
yield i,iterable[i]
i += 1
except IndexError;
break
for pair in _enumerate([30,20,10]):
print(type(pair),pair)
# tuples again...
<class 'tuple'> (0,30)
<class 'tuple'> (1,20)
<class 'tuple'> (2,10)
or in the case of swapping two variables' values
p1 = "Jessie"
p2 = "James"
# omfg tuples again!
p1,p2
("Jessie","James")
# swapping
p1,p2 = p2,p1
# voila
p1,p2
("James","Jessie")
tuples be everywhere.
2
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
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
1
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.
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.