Articles → Python → Tuples In Python

Tuples In Python






What Are Tuples?





Syntax


Variable_name = (element1,element 2,…..)



Example




classmates = ("Karan","sumit","amit") #declaring a tuple of classmates

print(classmates) # printing the value of tuples

classmates[1] = "Tarun" # assign the value at position 2

print(classmates) # printing the value of the tuple




('Karan', 'sumit', 'amit')
Traceback (most recent call last):
  File "C://python/datatype.py", line 5, in <module>
    classmates[1] = "Tarun"
TypeError: 'tuple' object does not support item assignment





Looping Through All The Elements In A Tuple




tuple = ("Banana","Orange","Grapes","Straw berry")

x= 0

while x < 4:
    print(tuple[x])
    x = x + 1




Picture showing the output of looping through all the elements in tuple



Specifying The Range




tuple = ("Banana","Orange","Grapes","Straw berry")

print(tuple[1:3])




Picture showing specifying the range in the tuple



Posted By  -  Karan Gupta
 
Posted On  -  Thursday, February 14, 2019
 
Updated On  -  Thursday, February 21, 2019

Query/Feedback


Your Email Id
 
Subject
 
Query/FeedbackCharacters remaining 250