Xtralien Scientific Python: Tuples
Tuples are similar to lists in Python in all except they cannot be modified once set. The only way to change a set stored in a variable is to overwrite the the variable with a new set with new elements.
Creating tuples is similar to creating lists. We can simply use the
() notation to create a tuple. This is analagous to the
 notation for lists. There is one additional difference however, in that tuples cannot have a length of \(0\).
A further caveat is that tuples of length \(1\) must also contain a comma. This is because brackets surrounding values are sometimes used to to define a scope when calculating values to adhere to correct order of operations.
a = (1,)
The above example will assign a tuple containing only the value
1 to the variable
a. Creating a that has a length larger than one is intuitive knowing the above.
a = (1, 2)
The example above shows how to create a tuple of length \(2\) containing the values
Accessing tuples is the same as accessing lists, including creating slices. This means that in terms of accessing elements in each, they are interchangable.
If we have the tuple
a = (1, 2, 3, 4)
Then, as in lists section, we can access single elements of the tuple.
b = a
This would set
b to the value
Likewise, we can take a slice of a tuple.
b = a[1:3]
This would set
b to the value of
Note: A slice is of an iterable is usually of the same type as the origin. e.g A slice of a list is a list and a slice of a tuple is a tuple.