Tuples in Python

A tuple is a sequence data type like the list.

But the difference is that a tuple is immutable which means that the contents in a tuple cannot be changed.

Like how lists use square brackets [], tuples use parentheses ().




Tuple Syntax

variable = (item1, item2, ..itemN)

variable = item1, item2, ..itemN

Items should be separated by comma (,) and using parentheses (()) is optional.

Example

numbers           = (0, 1, 2, 3, 4,5)       #same data type  
data              = ("Python", 3.64, 2018)  #different data type
no_parentheses    = "hello", 1, 12.98       #without parentheses

An empty tuple is constructed by using two parentheses (()) with nothing inside.

empty = ()  #empty tuple  

To construct a tuple with a single value we must include a comma (,) after that value, even though we have only one value.

single_valued = (3549,) #Single valued tuple





Printing the tuple elements

Example

#Python Tuples Example

numbers        = (0, 1, 2, 3, 4,5)       #same data type  
print(numbers)

data           = ("Python", 3.64, 2018)  #different data type
print(data)

no_parentheses = "hello", 1, 12.98       #without parentheses
print(no_parentheses)

empty          = ()                      #empty tuple
print(empty)

single_valued  = (3549,)                 #Single valued tuple
print(single_valued)


Topics You Might Like