A tuple in Python is a data structure which has a unique property that differentiates it from lists and dictionaries. It is immutable. This means, once the data inside tuples has been defined, it can't be programmatically changed by accessing the elements using indices. Tuples are declared using parentheses ()
whereas lists are declared using square brackets []
. But similar to lists, tuples are indexed from 0.
How to create a tuple?
There are many different ways of creating a tuple in python, we will cover a few of them in this tutorial.
Method 1: Creating an empty tuple using parentheses.
my_first_tuple = ()
print(my_first_tuple)
Method 2: Creating a tuple with elements defined directly inside it.
my_first_tuple = ('Studytonight', 'is', 'fabulous')
print(my_first_tuple)
Method 3: Creating a tuple without the usage of parentheses
my_first_tuple = 'Studytonight', 'is', 'fabulous'
print(my_first_tuple)
This way of creating a tuple is known as tuple packing. Since there is tuple packing, it is obvious to have a tuple unpacking feature as well.
Tuple unpacking can be done by assigning different variable names to the tuple. This will automatically map every variable name to every item in the tuple. For example,
m , n, o = my_first_tuple
print(m) # This prints Studytonight
print(n) # This prints is
print(o) # This prints fabulous
Output:
Studytonight
is
fabulous
Note: While creating a tuple with a single element, it is required to put a comma (,)
after defining the first element to clearly indicate that the data type of the element is a tuple. This can be done with or without using the parenthesis. For example,
my_first_tuple = ("hello",)
# or
my_first_tuple = "hello",
How do I access the elements in the tuple?
It can be accessed in the same ways as to how a list is accessed.
Tuple Index
The index operator []
can be used to access specific elements of a tuple. But if one tries to access elements which are not present in the index or whose index is higher than the size of the tuple itself, it gracefully raises an IndexError.
Let's take an example:
my_first_tuple = ('Studytonight', 'is', 'fabulous')
print(my_first_tuple[1]) # prints is
print(my_first_tuple[3]) # IndexError
Similar to lists, the last element in the tuple can be accessed using negative index -1. Also slicing works in the same way for tuples as for lists.
print(my_first_tuple[-1]) # prints fabulous
Conclusion
In this post, we understood what makes a tuple different from a list, ways of creating an empty tuple, adding elements to a tuple and accessing these elements using the index operator. Hope you understood it.
You may also like: