Tuples
Mutability
Sequential collections (so far):
string - immutable
list - mutable
tuple - immutable
A tuple, like a list, is a sequence of items of any type. Unlike lists, however, tuples are immutable.
Syntactically, a tuple is a comma-separated sequence of values. Although it is not necessary, it is conventional to enclose tuples in parentheses:
Tuples are useful for representing what other languages often call records — some related information that belongs together, like your student record. There is no description of what each of these fields means, but we can guess.
All info about Julia can be represented with one variable by using a tuple.
Tuples support the same sequence operations as strings and lists. For example, the index operator selects an element from a tuple.
Single element tuple
To create a tuple with a single element (but you’re probably not likely to do that too often), we have to include the final comma, because without the final comma, Python treats the (5)
below as an integer in parentheses:
Tuple assignment
Tuple of values can be assigned to a tuple of variables in a one line statement:
!!! ALERT!!! Both tuples must have equal amount of elements
Tuple on the left can be only variable, but on the right can hold values of variables (previously assigned to something). It is very useful for swapping values for variables:
Tuples as Return Values
A function (which can only return a single value), can create a single tuple holding multiple elements.
Last updated
Was this helpful?