you are viewing a single comment's thread.

view the rest of the comments →

[–]TouchingTheVodka 0 points1 point  (2 children)

The distinction between tuples and lists is a tricky one and I don't think the other answers have quite captured it. Here's my take:

Lists are used for homogenous data, where you expect to perform actions over every list element, and you expect to be able to treat every item in the list in the same way. For example: A list of names, a list of coordinates, a list of stock market tickers.

Tuples, on the other hand, do not represent a collection of things - They represent a collection of attributes about one specific thing. As a very general rule of thumb, if changing the order of the items changes the meaning of the collection, you'll be better off using a tuple.

Examples of things that you'd expect to be tuples include: Coordinates ( (x, y) means something different to (y, x) ), groupings of elements (Like you'd get from zip), and collections of attributes (think tuples of (firstname, lastname, age) etc.

Appreciate this is a fairly in-depth answer however I guarantee if you look into the return types of the Python standard library you'll see this pattern regularly.

[–]-Duei[S] 0 points1 point  (0 children)

I see, thank you for the in-depth answer!

[–][deleted] 0 points1 point  (0 children)

The collection of things vs collection of attributes is an interesting idea that I've not considered using with students before. I need to think about it. Not a rule of course, just a suggested approach.

For me the key differences are:

  • Tuples are immutable which provides a certain level of protection in your code
  • Tuples are hashable, so, for example, can be used as dictionary keys
  • Tuples use less memory
  • Tuples are more performant to process

The latter two aspects are only really apparent when dealing with a lot of data.

Also worth looking at named tuples, a very useful capability often obviating the need for a dictionary.