Data structures – Tuples
A tuple in Python is a sequence of objects.
They are used when we want to treat a sequence as a single object.
Examples of tuples can be the coordinates (x, y) or the definition of a color with its red, blue and green components (r, g, b)
The tuples are immutable, that is, they are constants that cannot be modified.
They are defined as a sequence of objects separated by commas and enclosed in parentheses.
Examples
xy = (10.20)
color = (10,20,30)
Operations between tuples
+ concatenates two tuples
* repetition of a tuple
[] select an element from the tuple
Examples
(2.3) + (5.6)
the tuple will be obtained (2,3,5,6)
2 * (1,2)
the tuple (1,2,1,2) will be obtained
t = (1,2)
t [1] = 2
Comparison operations are evaluated for each element in the tuple.
Example
(1.2) <(3.4)
evaluates to True. Actually compare 1 <2 and 2 <4
Assignment
In python there is multiple assignment that allows assigning values to different variables online
e.g
x, y = (5.6)
would assign x = 1 y = 6
Default operations
sum (tuple) – sum all the elements of the tuple
max (tuple) – maximum element
len (tuple) – returns the number of elements