Tuples

Overview

Tuples are one of the primary data types utilized in Python. They are declared using parentheses ( and can contain any data type:

my_tuple = (1,2,3,4,5.5,"some_text")

In general, when you see or think "parentheses" in Python, you should think tuples. However, there is one notable exception. When utilizing tuple comprehensions, you would expect that the logic within the parentheses would create a tuple object. For example, in the code below, you would expect the output to be a tuple with the values 0, 2, 4, 6. However this type of syntax creates a generator:

not_a_tuple = (i*2 for i in range(4))
print(not_a_tuple)
<generator object <genexpr> at 0x7ff1b0188510>

In order to make sure that the output is a tuple, you would need to explicitly declare it:

now_a_tuple = tuple(i*2 for i in range(4))
print(now_a_tuple)
(0,2,4,6)

Another key feature of tuples is that they are immutable (not mutable). This means that, once they are declared, they cannot be modified. For example, if you try to change a single element of a tuple after it is created, then Python will give an error:

my_tuple = (1,2,3,"tuples are cool")
my_tuple[3] = "I prefer lists"
Python error :(

If you do need to change an item, it is pretty straightforward to convert from a tuple to a list:

i_want_to_be_a_list = (1,2,3) # Right now it is a tuple.
now_its_a_list = list(i_want_to_be_a_list)
print(type(now_its_a_list))
<class 'list'>

Tuple Methods

The following is a table of tuple methods from w3schools.

Method Description

count()

Returns the number of times that a specified value occurs in a tuple

index()

Searches the tuple for a specified value, and returns the position where it was found

Tuple Indexing

Python indexing is a bit different from what you may be used to in R. It is worthwhile to review the Indexing section, to understand the differences in how the tuples and lists are indexed.