How Can We Help?
Introduction:
In this tutorial, we are going to explain how to use Python tuples with basic syntax and many examples for better understanding.
Python tuples (tup) is a form of data collection ,where different type of data can be stored and separated by commas(,). Tuple is enclosed in a pair of parenthesis ( ). and holds all values in a given order. (See the official python.org tuples docs.)
Syntax:
<tuple_variable_name>=(value1, value2,value3…)
Example (1) :
# single data type tuple
tup=('Country','State','City')
print(tup)
Example (1) Output:
(‘Country’, ‘State’, ‘City’)
In the above example, ‘tup’ is a tuple variable name and ‘Country ,State and City’ are tuple values.
Tuples can be number, string or both. The values in it need not to be of the same data type always.
Example (2) :
# multi data type tuple
mytuple=(1,'Python',5.2,'language!')
print(mytuple)
Example (2) Output:
(1, ‘Python’, 5.2, ‘language!’)
In the above example, ‘mytuple’ is a tuple variable name and ‘1, Python, 5.2 and language!’ are tuple values which are not of same data type.
Note: Tuples are immutable that means it can’t be changed and read-only list.
Empty tuple :
The empty tuple is written as two parentheses(), i.e. containing nothing.
Example (3) :
tuple=(), mytuple=()
In the above Example, ‘tuple’ and ‘mytuple’ are tuple variable name and two parentheses () shows empty tuple values.
Tuple with single element:
A single value tuple is containing only single value with comma and enclosed in pair of parenthesis ().
Example (4) :
number=(11,) , alphabet=('abc',)
In the above Example, ‘number’ and ‘alphabet’ are tuple variable name and the values as (11,) and (‘abc’,) shows the tuple with single values respectively.
Python tuples multiple assignment
We can assign multiple python tuples with its values in a single line by multiple tuple assignment.
Example (5) :
# multiple tuples assignment
number, alphabet= (1,2,3) , ('a','b','c')
print('number:',number)
print('alphabet:',alphabet)
Example (5) Output:
number: (1, 2, 3)
alphabet: (‘a’, ‘b’, ‘c’)
In the above Example, number and alphabet is tuple variable name and (1,2,3) and (‘a’, ‘b’, ‘c’) are respective values.
Accessing tuple values :
We use the square brackets [] along with the index to access the tuple value available at that index position. Tuples use positive index like 0,1,2… and negative index like -1,-2,-3…..to access the values.
Python tuples with positive and negative indexing:
Let’s take, tuple variable as:
prog_language=('Java','Ruby','C','C#','.Net','Python')
In the above image, we have given indexing to tuple values (‘Java’,’ruby’,’C’,’C#’,’.Net’,’python’). The positive indexing is shown in left to right direction and negative indexing is shown from right to left direction, same like string data type. To access the tuple values, we have to call the tuple index, as per below syntax.
Syntax:
<tuple_variable_name>[tuple index]
Example (6) :
prog_language=('Java','ruby','C','C#','.Net','python')
# original tuple values
print(' prog_language=', prog_language)
# tuple values after accessing the index [0] and [-2]
print('0th and 4th position tuple values:',prog_language[0],prog_language[-2])
Example (6) Output:
prog_language=(‘Java’,’ruby’,’C’,’C#’,’.Net’,’python’)
0th and 4th position tuple values: Java .Net
In the above Example, for tuple variable ‘prog_language’, we are accessing the 0th and 4th position of tuple values by positive index [0] and negative index [-2] respectively as prog_language[0], prog_language[-2]. Therefore, in print statement output is ‘Java’ which is at 0th and -6th position of tuple and ‘.Net’ which is at 4th and -2th position of tuple. (See Fig. 1 for tuple position)
Tuple index out of range index error
If we try to access the index of tuple which is not a part of tuple, then it raises an index error exception.
Example (7) :
alphabet=('a','b','c')
# out of range tuple index
print(alphabet[3])
Example (7) Output:
Traceback (most recent call last):
File “”, line 1, in
alphabet=(‘a’,’b’,’c’);print(alphabet[3])
IndexError: tuple index out of range
In the above Example, ‘alphabet’ is tuple variable name and it has 3 values only which has index as 0,1 and 2 but here, we are accessing 3rd index value by alphabet[3] in print statement which is not a part of tuple, so we got the IndexError as ‘tuple index out of range’ in output.
Python tuples slicing and substring
Accessing a contiguous sequence of values from a tuple is called a substring, and the process used for substring is called slicing. We can slice a tuple in both (left and right) direction same as tuple indexing.
Syntax:
<tuple_variable_name>[start position : end position]
<tuple_variable_name>[start position:]
<typle_variable_name>[:end position]
Here, start and end positions should be integer value.
Note: Tuple Slicing don’t consider the end position or index value after colon(:).
Example (8):
prog_language=('Java','ruby','C','C#','.Net','python')
# tuple values after slicing [1:3]
print('1st to 3rd position tuple values:' ,prog_language[1:3])
Example (8) Output:
‘1st to 3rd position tuple values: (‘ruby’, ‘C’)
In the above Example, for tuple variable ‘prog_language’, we are accessing the tuple values between 1st to 3rd position by prog_language[1:3]. Output is received as ‘ruby’ which is at 1st position of tuple and ‘C’ which is at 2nd position of tuple. Here, we have considered only 1st and 2nd position of tuple as 3rd position of tuple is not considered as the end position because slicing will not accept the values after colon(:).
Example (9):
prog_language=('Java','ruby','C','C#','.Net','python')
# tuple values after slicing [1:]
print(prog_language[1:])
Example (9) Output:
(‘ruby’, ‘C’, ‘C#’, ‘.Net’, ‘python’)
In the above Example, for tuple variable ‘prog_language’, we are accessing the tuple values from 1st position to end position of tuple by prog_language[1:]. Output is received as (‘ruby’, ‘C’, ‘C#’, ‘.Net’, ‘python’) which is excluding the 0th position of tuple. Here, end position is not mentioned in program so output shows all values of tuple from 1st index to last index because start position is 1.
Example (10):
prog_language=('Java','ruby','C','C#','.Net','python')
# tuple values after slicing [:4]
print(prog_language[:4])
Example (10) Output:
(‘Java’, ‘ruby’, ‘C’, ‘C#’)
In the above Example, for tuple variable ‘prog_language’, we are accessing the tuple values up to 4th position of tuple by prog_language[:4]. Output is received as (‘Java’, ‘ruby’, ‘C’, ‘C#’) which shows tuple values from 0th position to 3rd position. Here, 4th position is not considered because slicing not consider index values after colon(:), so the output is taken from 0th position as start position because tuple always start with 0th position and in program, start position is not mentioned.
Example (11):
prog_language=('Java','ruby','C','C#','.Net','python')
# tuple values after slicing [ : ]
print(prog_language[:])
Example (11) Output:
(‘Java’, ‘ruby’, ‘C’, ‘C#’, ‘.Net’, ‘python’)
In the above Example, for tuple variable ‘prog_language’, start and end position of tuple value is not mentioned in slicing code by prog_language[:] so output shows all values of tuple as (‘Java’, ‘ruby’, ‘C’, ‘C#’, ‘.Net’, ‘python’) which shows tuple values from 0th index to last index as explained already.
Update Tuple :
We can’t update a tuple by adding a new entry of value or modifying an existing entry of value. The reason is that tuples are immutable.
Example (12):
numtup=(1,2,6,7)
numtup[0]=22
print(numtup)
Example (12) Output:
Traceback (most recent call last):
File “”, line 1, in
numtup=(1,2,6,7);numtup[0]=22;print(numtup)
TypeError: ‘tuple’ object does not support item assignment
In the above Example , we are updating element [0] of tuple variable ‘numtup’ by numtup[0]=22 so in output ,we got type error i.e. ‘tuple’ object does not support item assignment.
We can use part of existing tuples to form a new tuples.
Example (13):
tup1=(1,2,6,7)
tup2=('a','b')
# new tuple from two old tuples
tup3=tup1 + tup2
print(tup3)
Example (13) Output:
(1, 2, 6, 7, ‘a’, ‘b’)
In the above Example, By using tuple variables ‘tup1’ and ‘tup 2’,we have created new tuple variable ‘tup3’ by tup3=tup1 + tup2 so we can say that tuple can’t modified but can be used to create a new tuple.
Python tuples Built-In Functions:
Python has following built-in tuple functions.
Sr. | Function | Description |
1 | min(tup) | It returns a minimum value of a tuple. |
2 | max(tup) | It returns a maximum value of a tuple. |
3 | len(tup) | It returns total length of a tuple, which is equal to the number of elements in the tuple. |
4 | type(tup) | It returns type of tuple , if passed variable is a tuple. |
5 | tuple(seq) | It converts a sequence/string into a tuple. |
6 | del(tuple) | It deletes whole tuple. |
7 | cmp(tuple1, tuple2) | Compares elements of both tuples. |
Python tuples Basic operations :
Sr. | Operation | Description |
1 | Concatenation(‘+’) | It adds two tuples |
2 | Repetition(‘*’) | It repeats element of tuple. |
3 | Membership(‘in’ & ‘not in’) | It returns True , if given element is present in tuple otherwise returns False. |
4 | Tuple Iteration | It returns element of tuple by using for loop with tuple. |
Python tuples built-in methods
Sr. | Operation | Description |
1 | tuple.count(object) | It returns count of how many times object occurs in tuple. |
2 | tuple.index(object) | It returns the lower index value of passed object in the list, if object is present in tuple. |
In this tutorial, you have learned how to use python tuples.
If you have an inquiry or doubt don’t hesitate to leave them in the comment section. we are waiting for your feedback.But remember to understand the concept very well, you need to practice more.
Hopefully, it was clear and concise.
Python tutorials list:
- Python tutorials list : access all python tutorials.