In This Article You Will Learn About Python Tuple Method
Python Tuple Method – Before moving ahead, let’s know about some Introduction to Python Tuple concept
Tuple – It is a collection and contains elements in ordered and unchangeable form. It represents with round brackets.
Creating Tuple with an element
Create Tuple with One Item – To create tuple with one item it is required to add a comma after element otherwise Python will consider it as string.
Example 10- Converting tuple type to list type.
x = ('a',) print(type(x)) x = ('a') print(type(x))
Removing/deleting Tuple Element
Remove element – Tuple is unchangeable or immutable. Once tuple element created, it can not be removed. But whole tuple can be deleted.
Example 11- Removing an element of Tuple.
x = ('Welcome' , 'programming' , 'language') x.remove('programming') print(x)
Example 12- Deleting whole Tuple.
x = ('Welcome' , 'programming' , 'language') del x print(x)
Join Tuple – In Python, Tuple can be easily joined or concatenated by using + operator.
Example 20- Concatenation of two Tuples.
x = (1 , 2 , 3) z = (4 , 5 , 6) print(x + z)
Use of Asterisk*
Asterisk in Tuple – If number of values is less than number of variables then, add an Asterisk (*) to the variable name and the rest of value will be assigned to the variable.
Example 21- Adding the rest of value to the last string.
If an Asterisk add to the variable except present at the last position, then, Python will assign values to the variables until the values set off with variables and matches values with the variables.
Example 22- Adding the rest of value to the second last string.
The Tuple() Constructor – It uses to construct or make new Tuple.
Example 21- Use of constructor to make new Tuple.
x = tuple(('a' , 'b' , 'c')) print(x)
Tuple Methods – Python has a set of built-in methods that can be used on Tuple.
Some of them we have already discussed rest of we are going to discuss now.
count() method – It returns the number of specified value.
Syntax - Tuple.count(value) Parameter values - It is required argument and takes letter or word which is to be counted.
Example 22- Use of count() method to count specified value.
x = 'language' z = x.count('a') print(z)
index() method – It returns the index number of first appeared element of the specified value.
Syntax - Tuple.index(value) Parameter Values - It is required argument and takes element which is to be indexed
Example 23- Use of index() method to get index number of particular letter.
x = ('a', 'b', 'c', 'd') print(x.index('c'))
If you find anything incorrect in above discussed topic and have any further question, please comment down below.
Like us on