r/learnpython • • Mar 27 '23

Actually using a tuple

Can someone, please, give me a "real-world" example on the use of a tuple? I'm learning through w3schools. The idea of a tuple sort of makes sense, but I have no idea how it would/could be applied.

147 Upvotes

64 comments sorted by

View all comments

5

u/[deleted] Mar 27 '23 edited Apr 20 '23

The tuple comes from discrete mathematics. It is a finite, ordered sequence of objects.

  • It is used to represent mathematical objects. For example, a Turing machine is formally defined as a 5-tuple, where each of the five elements in the tuple is used to define how the machine works.

  • It is used to order the elements in a sequence. The first five elements of the Fibonacci sequence can be defined by the tuple (0, 1, 1, 2, 3).

  • It is used to represent the arguments to a function. Where function(arg_1, arg_2) is the invocation of a function, that sequence of arguments is, mathematically-speaking, a tuple. (Whether or not it is treated that way by Python, I have no clue.)

The name is derived from the word "multiple" because, unlike a set, it allows for multiplicity in its elements. Multiplicity means that something can hold multiple of the same element: (0, 1, 1, 2, 3). Compare this to a set, which would interpret the same elements as {0, 1, 2, 3}. This is the characteristic advantage of using a tuple.

However, a list can also do this. A list is also ordered. So why use a tuple over a list? Well, another advantage of using a tuple is that it is immutable. If you declare a tuple to be (1, 2, 3), then you cannot add, remove, or change anything. This is what makes it different from a list.

Immutability also makes it hashable which means that it can be stored in a set: {(1, 2, 3)} or as the key to a dict: {(1, 2, 3): 'tuple'}. A list does not have this ability.

16

u/LuckyNumber-Bot Mar 27 '23

All the numbers in your comment added up to 69. Congrats!

  5
+ 1
+ 1
+ 2
+ 3
+ 5
+ 8
+ 1
+ 2
+ 1
+ 1
+ 2
+ 3
+ 5
+ 1
+ 2
+ 3
+ 5
+ 1
+ 2
+ 3
+ 1
+ 2
+ 3
+ 1
+ 2
+ 3
= 69

Click here to have me scan all your future comments.
Summon me on specific comments with u/LuckyNumber-Bot.

6

u/[deleted] Mar 27 '23 edited Apr 20 '23

Nice

6

u/imthebear11 Mar 27 '23

Holy shit nice