Tuple

Python Tuple tutorial

A tuple is an immutable list of values. Tuples are one of Python’s simplest and most common collection types, and can be created with the comma operator(tup = 1, 2, 3, 4)

Syntactically, a tuple is a comma-separated list of values:

tup = 'a','b', 'c','d','e','f'
print(tup)

#Output
('a', 'b', 'c', 'd', 'e', 'f')

Although not necessary, it is common to close tuples in parentheses:

tup = ('a','b','c','d','e','f)
print(tup)

#Output
('a', 'b', 'c', 'd', 'e', 'f')

To create a tuple with single value, you have to include a final comma:

tup = 'Book',
print(tup)
print(type(tup))

#Output
('Book',)
class 'tuple'

Tuples are Immutable

One of the main differences between Lists and tuples in python is that tuples are immutable, that is, one cannot add or modify items once the tuple is initialized. for example:

t = (1, 4, 5, 6)
#to change value at 0 1st position
t[0]= 2
print(t)

#Output gives error
Traceback (most recent call last):
   t[0]= 2
TypeError: 'tuple' object does not support item assignment

Similarly, tuples does not have .append and .extend methods as list does.

Previous||Next Chapter