Tuples in Python with examples
A Tuple in Python is a collection of immutable objects that are separated by commas. Here immutable objects mean those objects that can’t be changed or update.
Tuples in Python generally look like lists. But the difference between a Python tuple and a list is that tuple uses parentheses instead of square brackets. Also, objects in tuples can’t be changed whereas items of a Python list can be changed or updated.
Example of tuples in Python
Below is an example of a Tuple:
my_tuple = ('shirt', 'pant', 'skirt', 'shoes', 'watch')
Select a tuple by index number
Just like a Python list, we can also get the value of a tuple object by its index number with the same way as we can see in lists.
For example, if we want to get the object of the index number 3 then below is how we can do it:
The above code will give the output that is given below:
Slicing in tuple
Also, we can use slicing feature in our tuple as we can see below:
It will give us the output:
('shirt', 'pant', 'skirt')
So we can see that getting the value of a tuple item and apply the slicing process to a tuple is the same as we can see in the case of a Python list.
Example Python code with tuple
You can run the Python code that you can see below on your system:
my_tuple = ('shirt', 'pant', 'skirt', 'shoes', 'watch') print(my_tuple) print(my_tuple) print(my_tuple[0:3])
The above code will print the tuple, get the value of tuple with item index number 3 and give the output after slicing a tuple. See the output below:
('shirt', 'pant', 'skirt', 'shoes', 'watch') shoes ('shirt', 'pant', 'skirt')
We can add two or more tuples and create a new tuple. below is how we can do it:
my_tpl1 = ('bag', 215, 'red', 56, 'basket') my_tpl2 = ('star', 'moon', 865, 77) my_tpl3 = my_tpl1 + my_tpl2 print(my_tpl3)
if we run our above Python code, then we will able to see a new tuple. The output of the code will be:
('bag', 215, 'red', 56, 'basket', 'star', 'moon', 865, 77)
We can see that we have created a new tuple.
I hope, from this article, you got some idea on tuples in Python. Also, you have learned how to get a tuple item value by index number, how to slice tuple and how to create a new tuple by adding two or more tuples.