r/learnpython • u/Pure-Homework681 • 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
5
u/[deleted] Mar 27 '23 edited Apr 20 '23
The
tuplecomes 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 aset, which would interpret the same elements as{0, 1, 2, 3}. This is the characteristic advantage of using atuple.However, a
listcan also do this. Alistis also ordered. So why use atupleover alist? Well, another advantage of using atupleis 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 alist.Immutability also makes it hashable which means that it can be stored in a
set:{(1, 2, 3)}or as the key to adict:{(1, 2, 3): 'tuple'}. Alistdoes not have this ability.