Python Tuples
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.
Example
#creating a tuple
my_tuple = ("I", "am", "Learning", "Python")
#aceessing tuple items
print(my_tuple[0]) #outputs: I
print(my_tuple[1]) #outputs: am
print(my_tuple[2]) #outputs: Learning
print(my_tuple[3]) #outputs: Python
Tuple Length
In order to know, how many items a tuple has, we can use the len()
function. Here is an example:
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:
Example
tupleA = ("Python", "is")
tupleB = ("Easy", "to", "Learn")
print (tupleA + tupleB) #Outputs: ('Python', 'is', 'Easy', 'to', 'Learn')
Deleting a Tuple
Example
tupleA = ("Python", "is"," Easy", "to", "Learn")
del tupleA
print(tupleA)
# it will produce an error
Nesting of Python Tuples
Example
#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 reversed()
function
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:
Example
tuple1 = (1, 2, 3, 4, 5)
for element in tuple1:
print(element)
Output
1 2 3 4 5
Share This Post!
3 thoughts on “Python Tuples”