Python Tuple
Python Tuple
Python Tuple
Tuple
• Tuples are used to store multiple items in a single variable.
• Tuple is one of 4 built-in data types in Python used to store collections of data, the other 3 are
• List,
• Set, and
• Dictionary
• Tuples are like lists, but their elements are fixed; that is,
• once a tuple is created, one cannot add new elements, delete elements, replace elements, or reorder the elements in
the tuple
t1 = () # Create an empty tuple
t2 = (1, 3, 5) # Create a tuple with three elements
# Create a tuple from a list
t3 = tuple([2 * x for x in range(1, 5)])
# Create a tuple from a string
t4 = tuple("abac") # t4 is ['a', 'b', 'a', 'c']
Tuple vs List
Accessing Values in Tuples in Python
• Method 1: Using Positive Index
var = ("Geeks", "for", "Geeks")
print("Value in Var[0] = ", var[0])
print("Value in Var[1] = ", var[1])
print("Value in Var[2] = ", var[2])
tuple1 = (0, 1, 2, 3)
tuple2 = ('python', 'geek')
tuple1 = (0, 1, 2, 3)
tuple2 = ('python', 'geek')
tuple3 = (tuple1, tuple2)
print(tuple3)
Repetition Tuples
# Code to create a tuple with repetition
tuple3 = ('python',)*3
print(tuple3)
Finding Length of a Tuple
# Code for printing the length of a tuple
list1 = [0, 1, 2]
print(tuple(list1))
print(tuple('python')) # string 'python'
Obtain a list from a tuple
tup = ('geek',)
n = 5 # Number of time loop runs
for i in range(int(n)):
tup = (tup,)
print(tup)
No Enclosing Delimiters
• Any set of multiple objects, comma-separated, written without
identifying symbols, i.e., brackets for lists, parentheses for tuples, etc.,
default to tuples