Python Tuples are ordered and immutable collection of elements, enclosed in rounded brackets (“tuple elements“).
Tuples is a built-in data type in Python. Tuple is somewhat similar to Lists in python. But Tuples are ordered, which means items in tuple have a specified order and the order will never change. Tuples are also immutable, means we can’t add or remove any item from the tuple after it is created.
Here is an example of how you can create a tuple in Python.
tuple_name = ("item1", "item2", "item3")
If you want to create a tuple with only one item, then you must need to add comma (,) at the end of the item. Otherwise, Python will not be able to recognize it as a tuple.
Accessing Tuple Items
To access the tuple items, we have to refer to their index numbers. item1 has index number 0 rather than 1. item2 has index number 1 and so on. In an example below we will write a code and access the items in a tuple.
#creating a tuple my_tuple = ("I", "am", "Learning", "Python") #aceessing tuple items print(my_tuple) #outputs: I print(my_tuple) #outputs: am print(my_tuple) #outputs: Learning print(my_tuple) #outputs: Python
In order to know, how many items a tuple has, we can use the
len() function. Here is an example:
#creating a tuple my_tuple = ("I", "am", "Learning", "Python") #calculating tuple length print(len(my_tuple)) #outputs: 4
Add Tuples in Python (Concatenation)
We can add two or more tuples together using the plus (+) operator. Here is an example:
tupleA = ("Python", "is") tupleB = ("Easy", "to", "Learn") print (tupleA + tupleB) #Outputs: ('Python', 'is', 'Easy', 'to', 'Learn')
Deleting a Tuple
tupleA = ("Python", "is"," Easy", "to", "Learn") del tupleA print(tupleA) # it will produce an error
Nesting of Python Tuples
#creating nested tuples tupleA = ("Python", "is", "Easy") tupleB = ("Python", "is", "Amazing") tupleC = (tupleA, tupleB) print (tupleC) # outputs: (('Python', 'is', 'Easy'), ('Python', 'is', 'Amazing'))
Reverse a Python Tuple
We can reverse a tuple in python using the
reversed() function or by Tuple slicing. Here is an example of both:
Reverse a Tuple Using
tupleA = (1, 2, 3, 4, 5, 6) #reverse a tuple rev = tuple(reversed(tupleA)) print(rev) #outputs: (6, 5, 4, 3, 2, 1)
Reverse a Tuple Using tuple slicing
tupleA = (1, 2, 3, 4, 5, 6) #reverse a tuple rev = (tupleA[::-1]) print(rev) #outputs: (6, 5, 4, 3, 2, 1)
Tuples in Loop
Like any other iterable in Python, tuples can also be used in loops. A for loop can be used to go through the components of a tuple. Here is an example:
tuple1 = (1, 2, 3, 4, 5) for element in tuple1: print(element)
1 2 3 4 5
Share This Post!