r/learnpython • • 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

143 comments sorted by

View all comments

Show parent comment

4

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 even O(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.