Tuple in python

2 min read
Tuples is a immutable once its define then we can not change it. for using this we use the syntax of parentheses “( )“
#Syntax
masala_spices = ("cardamom", "cloves", "cinnamon")
print(masala_spices)
For accessing the value of the tuple first we need to know how much members in the tuple and then we use the tuple aging see the example then its will clear better.
masala_spices = ("cardamom", "cloves", "cinnamon")
(spice1, spice2, spice3) = masala_spices #here we are storing the all values of tuple in to the another variables
print(f"Main masala spices: {spice1}, {spice2}, {spice3}") #Output: Main masala spices: cardamom, cloves, cinnamon
we can store the values in the ratio and this uses the tuple behind the scene. and we can also swap the values.
ginger_ratio, cadramom_ratio = 2, 1
print(f"Ratio is G :{ginger_ratio} and C: {cadramom_ratio}") # Output: Ratio is G :2 and C: 1
ginger_ratio, cadramom_ratio = cadramom_ratio, ginger_ratio # Swaping the values
print(f"Ratio after swap is G :{ginger_ratio} and C: {cadramom_ratio}") # Output: Ratio after swap is G :1 and C: 2.
Membership Testing: We are checking the is this available in the tuple or not. Make sure this is case sensitive.
masala_spices = ("cardamom", "cloves", "cinnamon")
# membership testing
print(f"Is cinnamon in masala spices ? {'cinnamon' in masala_spices}") # Output: Is cinnamon in masala spices ? True.
print(f"Is ginger in masala spices ? {'ginger' in masala_spices}") # Output: Is ginger in masala spices ? False.
0
Subscribe to my newsletter
Read articles from Shubham Bhardwaj directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
