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 generate, 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 the output is a tuple you would need to explicity declare it:
now_a_tuple = tuple(i*2 for i in range(4)) print(now_a_tuple)
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 Python will error:
my_tuple = (1,2,3,"tuples are cool") my_tuple = "I prefer lists"
Python error :(
If you do need to change an item it’s pretty straightforward to convert from a tuple to a list:
i_want_to_be_a_list = (1,2,3) # Right now it's a tuple. now_its_a_list = list(i_want_to_be_a_list) print(type(now_its_a_list))
The following is a table of tuple methods from w3schools.
Returns the number of times a specified value occurs in a tuple
Searches the tuple for a specified value and returns the position of where it was found
Python indexing is a bit different from what you may be used to in R. It’s worthwhile to review the Indexing section to understand the differences in how the tuples and lists are indexed.