What is Python Tuple type
Get to know tuple
Tuple is a sequence of data and cannot be changed. Tuples are enclosed in parentheses.
print (1, 2, 3)
The code above generates the following result.
We can also create a tuple by using comma only without parentheses.
x = 1 ,2, 3
print x
The code above generates the following result.
The empty tuple is written as two parentheses containing nothing:
print ()
The code above generates the following result.
To write a tuple containing a single value, we have to include a comma, even though there is only one value.
print (42,)
print 3*(40+2)
print 3*(40+2,)
The code above generates the following result.
The last 3*(40+2,)
is Tuple repitition which is like the following.
print (1, 2) * 4 # repitition
The code above generates the following result.
tuple
itself cannot be changed, but
tuple
can contain mutable objects that can be changed.
t = (['xyz', 123], 23, -103.4)
print t# w ww. j a v a 2 s . com
print t[0][1]
t[0][1] = ['abc', 'def']
print t
aTuple = (123, 'abc', 4.56, ['inner', 'tuple'], 7-9j)
anotherTuple = (None, 'something to see here')
print aTuple
print anotherTuple
emptiestPossibleTuple = (None,)
print emptiestPossibleTuple
The code above generates the following result.
Unpacking tuple
We can unpack a tuple value into several values and assign multiple values at once.
v = ('a', 'b', 'e')
(x, y, z) = v# from w w w . ja v a 2s. c o m
print x
print y
print z
The code above generates the following result.
Convert to tuple
We can use tuple function to convert other data type to a tuple.
print tuple([1, 2, 3])
print tuple('abc')
print tuple((1, 2, 3))
The code above generates the following result.
Compare two tuples
print (4, 2) < (3, 5)
print (2, 4) < (3, -1)
print (2, 4) == (3, -1)
print (2, 4) == (2, 4)
The code above generates the following result.