Tuples in Python
In this tutorial we are going to learn:Â
- Creating a Tuple
- Accessing Tuple Items
- Checking Tuple Items and using the len() function
Â
Â
Creating a Tuple
Â
- A tuple is a collection that is ordered and unchangeable.
- We cannot add and remove item from it.
- Tuples are written with round brackets or comma.
- To create a tuple , we use round brackets or comma. Look at the example below.
Â
Example :
# ways to create a tuple
first_tuple = (1, 2, 3)
second_tuple = 1, 2
third_tuple = 1,
fourth_tuple = ()
print(type(first_tuple))
print(type(second_tuple))
print(type(third_tuple))
print(type(fourth_tuple))

Â
- Creating tuple using the tuple () function.Â
Â
Example :
# using of tuple() function
text = "Hello World"
my_list = [1, 2, 3, 4, 5]
first_tuple = tuple(text)
second_tuple = tuple(my_list)
print(first_tuple)
print(second_tuple)

Â
Â
Â
Accessing Tuple Items
Â
You can use square parentheses to access tuples items .
Example :
#accessing tuples
first_tuple = (1, 2, 3, "a", "b")
second_tuple = ("c", "d", "e")
last = first_tuple + second_tuple # combining tuples
print(last)
print(last[0])
print(last[-1])
print(last[0:4])

Checking Tuple Items and Using len() Function
- We use the in keyword to learn if the item exists in the list .
- To get tuple’s lenght, you can use the len() function
Example :
#checking item in the tuple
my_tuple = (1, 2, 3, 4, 5)
if 1 in my_tuple:
print("it is in the tuple")
# using len() function
print(f"Tuple Lenght : ", len(my_tuple))

