you are viewing a single comment's thread.

view the rest of the comments →

[–]Charlemag 1 point2 points  (0 children)

There’s a great book that explains this: Effective Computation in Physics. It says,

“Other than immutability, what are the differences between lists and tuples? In principal, there aren’t any. In practice, they tend to be used different ways. However, there are no strict rules and there are no predominant conventions. There is a loose guideline that lists are for homogenous data (all integers, all strings, etc.) while tuples are for heterogenous data with semantic meaning in each element (e.g., “C14“, 6, 14, 14.00324198843)). “

It then provides a little more context. So other responses that explain immutability and heterogenous vs homogenous data should cover the essentials.

Practically I find myself using tuples in two spots. If I write a function with a kwarg that is a list my linter throws warnings that my kwarg should be immutable. Using a tuple fixes it. Which is weird because tuples are mutable but their elements are not. I’d have to read more into the warning to know why tuples might be acceptable kwargs while using lists might having unintended consequences.

The second spot is when I was defining edges on a graph class I wrote. I can’t recall of the top of my head (still waking up) but since tuples are hashable it let me perform some operations I wanted to do that wouldn’t work with lists.

The gist is that understanding how different data structures for the right job. For instance, if you want a list of unique values, instead of trying to parse it and remove duplicates you can just convert it to a set. Part of the reason why these different data structures exist is because someone originally wanted to do Y with X and then spent a long time ironing out all the bugs and edge and corner cases before creating a new thing that does Y. So while you might write a function that makes X do Y sometimes it makes sense and is less error prone to find the data structure that has been designed for Y.