Tuple Data Type In
Python:
§ Tuple data type is exactly same as list data type except that it is immutable, we
cannot change values.
§ It is fixed-length and immutable.
§ The values in the tuple cannot be changed nor the values be added to or removed
from the tuple
§ Tuple
elements can be represented within parenthesis.
§ Tuple
Can be made using the parentheses.
§ Lists
are enclosed in brackets [ ] and their elements and size can be changed, while
tuples are enclosed in parentheses ( ) and cannot be updated. Tuples are immutable.
Difference Between List and Tuple
List
|
Tuple
|
List is used for holding multiple
element.
|
Tuple is also used for holding multiple
element.
|
heterogeneous
objects are allowed in List
|
heterogeneous
objects also are allowed in Tuple.
|
duplicates are allowed in List.
|
duplicates are allowed In Tuple.
|
List
is Growable in nature
|
Tuple
is fixed-length in nature
|
List is a mutable type object
|
Tuple is an immutable type object
|
In
List, values should be enclosed within square brackets [].
|
In
Tuple, values should be enclosed within parentheses ().
|
Different Ways to Creating a Tuple in Python
§ tuple
Can be made using the parentheses.
§ We
can create a tuple by placing values with-in parentheses and values should be
separated by comma.
my_tuple=(value1,value2,value3,.....valuen)
my_tuple=(10,20,30)
print(my_tuple)
v We can
create empty tuple object as follows.
§ We
can create an empty tuple with-out placing any value with-in parentheses.
# Empty tuple
my_tuple = ()
print(my_tuple) # Output: ()
v We can
create tuple object with some element as follows.
# Tuple having integers
my_tuple = (10, 20, 30,40,50)
print(my_tuple) # Output: (10, 20, 30, 40, 50)
# tuple with mixed datatypes
my_tuple = (10, "Hello", 5.6)
print(my_tuple) # Output: (10, 'Hello', 5.6)
v We can
create tuple object with-out parentheses also as follows.
Packing Tuples
§ Tuple
can be made without using brackets also This is known as tuple packing.
§ We
can say that a tuple is a comma-separated list of values:
my_tuple=value1, value2, value3, valuen
§ The
assignment a = 1, 2, 3 is also called packing because it packs values together
in a tuple.
my_tuple=10,20,30
print(my_tuple)#The Output (10, 20, 30)
Unpacking Tuples
§
To
unpack values from a tuple and do multiple assignments use
# tuple unpacking is also possible
a,b,c=(10,20,30)
print(a)#The Output 10
print(b)#The Output 20
print(c)#The Output 30
Note:-
§ The
symbol _ can be used as a disposable variable name if one only needs some
elements of a tuple, acting as a placeholder.
a = 1, 2, 3, 4
_, x, y, _ = a
print(_)# The output 4
print(x)# The output 2
print(y)# The output 3
print(_)# The output 4
Can we create a tuple with single element?
§ It
is a bit tricky to make a tuple with a single element.
my_tuple=(10)
print(my_tuple)#The
Output 10
print(type(my_tuple))#The Output <class 'int'>
my_tuple=('hello')
print(my_tuple)#The Output hello
print(type(my_tuple))#The Output <class 'str'>
Note:-
§ A
single value in parentheses is not a tuple
§ Keeping
only one value is not enough within the tuple We will need a trailing comma to
indicate tuple.
§ you
have to include a final comma
my_tuple=(10,)
print(my_tuple)#The Output (10,)
print(type(my_tuple))#The Output <class 'tuple'>
my_tuple=('hello',)
print(my_tuple)#The
Output ('hello',)
print(type(my_tuple))#The
Output <class 'tuple'>
Single
element tuples:
x, =1,
print(x) #The Output 1
print(type(x)) #The Output <class 'int'>
y=1,
print(y)#The Output (1,)
print(type(y)) #The Output <class 'tuple'>
v We can
create tuple object with tuple() function as follows.
§ The tuple() function creates a tuple from an
iterable object.
§ An iterable may be either a sequence, a container
that supports iteration.
my_tuple=tuple()
print(my_tuple)#The
Output ()
#Create an tuple by passing string as a sequence
my_tuple=tuple('hello')
print(my_tuple)#The Output ('h', 'e', 'l', 'l', 'o')
How to access Element from the Tuple
§ The
elements of a tuple can be accessed via an index, or numeric representation of
their position. Lists in Python are zero-indexed meaning that the first element
in the list is at index 0, the second element is at index 1 and so on:
§ Accessing tuple elements using positive indexes
nums=(10,20,30,40,50)
print(nums[0])#The Output 10
print(nums[1])#The Output 20
print(nums[2])#The Output 30
print(nums[3])#The Output 40
print(nums[4])#The Output 50
Note:
§ TypeError:
If you do not use integer indexes in the tuple. For example my_data[2.0] will raise this error. The index must always be an integer.
§ IndexError:
Index out of range. This error occurs when we mention the index which is not in the range. For example, if a tuple has 5 elements and we try to access the 7th element then this error would occurr.
§ Accessing tuple elements using negative indexes
§ Indices
can also be negative which means counting from the end of the list (-1 being
the index of the last element).
nums=(10,20,30,40,50)
print(nums[-1])#The Output 50
print(nums[-2])#The Output 40
print(nums[-3])#The Output 30
print(nums[-4])#The Output 20
print(nums[-5])#The Output 10
Iterating
Through a Tuple
§ Using
a for loop we can iterate through each item in a tuple.
nums=(10,20,30,40,50)
for n in nums:
print(n)
§ You
can also get the position of each item at the same time Using enumerate
function:
nums=(10,20,30,40,50)
for (index, item) in enumerate(nums):
print('The
item in position {} is: {}'.format(index, item))
Output:
The item in position 0 is: 1
The item in position 1 is: 2
The item in position 2 is: 3
The item in position 3 is: 4
The item in position 4 is: 5
The item in position 5 is: 6
§
The other way of iterating a tuple based
on the index value:
nums=(10,20,30,40,50)
for i in range(0,len(nums)):
print(i,'->',nums[i])
Output:
0 -> 1
1 -> 2
2 -> 3
3 -> 4
4 -> 5
5 -> 6
Tuple Operators In Python
The +
Operator
§ The
+ operator is Used to concatenating to tuple.
§ The
simplest way to concatenate tuple1 and tuple2
merged = tuple1 + tuple2
tuple1=(10,20,30)
tuple2=(40,50)
merge_tuple=tuple1+tuple2
print('tuple1 =',tuple1)
print('tuple2
=',tuple2)
print('merge_tuple= ',merge_tuple)
Output:
tuple1 = (10, 20, 30)
tuple2 = (40, 50)
merge_tuple= (10, 20, 30,
40, 50)
tuple1=(10,20,30)
tuple2=(40,50,60)
for a, b in zip(tuple1, tuple2):
print(a, b)
The *
Operator
§ The
* operator creates multiple copies of a string.
§ Replication
– multiplying an existing tuple by an integer will produce a larger tuple
consisting of that many copies of the original.
tuple1=(10,20,30)
print(tuple1*3)
tuple2=('a','b','c')
print(tuple2*3)
Output:
(10, 20, 30, 10, 20,
30, 10, 20, 30)
('a', 'b', 'c', 'a',
'b', 'c', 'a', 'b', 'c')
The in Operator
Checking Membership(Tuple
Contains):
§ By using in
operator, we can check whether an item is in a tuple or not.
tuple1=(10,20,30)
print(10 in tuple1)# The Output True
print(10 not in tuple1)# The Output False
print(40 not in tuple1)# The Output True
tuple2=('a','b','c')
print('a' in tuple2)# The Output True
print('a' not in tuple2)# The Output False
print('d' not in tuple2)# The Output True