Tuple count() Method in Python Examples
Count Frequency of Element in a Tuple in Python
Here we are calculating the total occurrence of a particular element in the given tuple using the count method.
Python3
# Creating tuples Tuple1 = ( 0 , 1 , 2 , 3 , 2 , 3 , 1 , 3 , 2 ) Tuple2 = ( 'python' , 'geek' , 'python' , 'for' , 'GFG' , 'python' , 'geeks' ) # count the appearance of 3 res = Tuple1.count( 3 ) print ( 'Count of 3 in Tuple1 is:' , res) # count the appearance of python res = Tuple2.count( 'python' ) print ( 'Count of Python in Tuple2 is:' , res) |
Output:
Count of 3 in Tuple1 is: 3 Count of Python in Tuple2 is: 3
Count List Elements Inside Tuple
Here we are calculating the total occurrence of a particular element, which in this case is a list and tuple inside a tuple using the count method.
Python3
# Creating tuples Tuple = ( 0 , 1 , "GFG" , [ 3 , 2 ], 1 , [ 3 , 2 ], 'geeks' , ( 0 ), ( 'G' , 'F' )) # count the appearance of [3, 2] res = Tuple .count([ 3 , 2 ]) print ( 'Count of [3, 2] in Tuple is:' , res) |
Output:
Count of [3, 2] in Tuple is: 2
Count Elements that do not exist in the Tuple
Here we are calculating the total occurrence of a particular element in the given tuple using the count method that actually does not exist in the tuple.
Python3
# Creating tuples Tuple1 = ( 0 , 1 , 2 , 3 , 2 , 3 , 1 , 3 , 2 ) Tuple2 = ( 'python' , 'geek' , 'python' , 'for' , 'GFG' , 'python' , 'geeks' ) # count the appearance of 3 res = Tuple1.count( 5 ) print ( 'Count of 5 in Tuple1 is:' , res) # count the appearance of python res = Tuple2.count( 'w3wiki' ) print ( 'Count of w3wiki in Tuple2 is:' , res) |
Output:
Count of 5 in Tuple1 is: 0 Count of w3wiki in Tuple2 is: 0
Counting occurrences of Tuples in a Tuple
In this example, we are nesting tuples inside a tuple and we check how many times a tuple is inside a tuple is occurring.
Python3
my_tuple = (( 1 , 2 ), ( 'a' , 'b' ), ( 1 , 2 ), ( 'c' , 'd' ), ( 'a' , 'b' )) count_tuple = my_tuple.count(( 1 , 2 )) print (count_tuple) count_xy = my_tuple.count(( 'x' , 'y' )) print (count_xy) |
Output :
2 0