Python | Count tuples occurrence in list of tuples
Many a time while developing web and desktop product in Python, we use nested lists and have several queries about how to find count of unique tuples. Let’s see how to get count of unique tuples in given list of tuples.
Below are some ways to achieve the above task.
Method #1: Using Iteration
# Python code to count unique # tuples in list of list import collections Output = collections.defaultdict( int ) # List initialization Input = [[( 'hi' , 'bye' )], [( 'Geeks' , 'forGeeks' )], [( 'a' , 'b' )], [( 'hi' , 'bye' )], [( 'a' , 'b' )]] # Using iteration for elem in Input : Output[elem[ 0 ]] + = 1 # Printing output print (Output) |
chevron_right
filter_none
Output:
defaultdict(<class 'int'>, {('Geeks', 'forGeeks'): 1, ('hi', 'bye'): 2, ('a', 'b'): 2})
Method #2: Using chain
and Counter
# Python code to count unique # tuples in list of list # Importing from collections import Counter from itertools import chain # List initialization Input = [[( 'hi' , 'bye' )], [( 'Geeks' , 'forGeeks' )], [( 'a' , 'b' )], [( 'hi' , 'bye' )], [( 'a' , 'b' )]] # Using counter and chain Output = Counter(chain( * Input )) # Printing output print (Output) |
chevron_right
filter_none
Output:
Counter({('hi', 'bye'): 2, ('a', 'b'): 2, ('Geeks', 'forGeeks'): 1})
Recommended Posts:
- Python | Find the tuples containing the given element from a list of tuples
- Python | Convert string tuples to list tuples
- Python | Remove duplicate tuples from list of tuples
- Python | Remove tuples having duplicate first value from given list of tuples
- Python | Remove tuples from list of tuples if greater than n
- Python | Combining tuples in list of tuples
- Python | Program to count duplicates in a list of tuples
- Python | How to Concatenate tuples to nested tuples
- Python | Min and Max value in list of tuples
- Python | Summation of tuples in list
- Python | Get unique tuples from list
- Python | Unzip a list of tuples
- Python | Group tuples in list with same first value
- Python | List of tuples to String
- Python | Summation of two list of tuples
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.