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)) 
0 0 vote
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments