Articles → Python → Tuples In Python

Tuples In Python






What Are Tuples?





Syntax


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



Example




classmates = ("Karan","sumit","amit")

print(classmates)

classmates[1] = "Tarun"

print(classmates)




  1. In the first line, we are declaring a tuple classmates.
  2. In the second line, we are printing the value of tuples.
  3. In the third line, we are trying the assign the value at position 2.
  4. In last line, we are printing the value of 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 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

Click to Enlarge


Specifying The Range




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

print(tuple[1:3])




Picture showing specifying the range in the tuple

Click to Enlarge


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