![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Python program to count Bidirectional Tuple Pairs
When it is required to count the number of bidirectional tuple pairs in a list of tuples, the list can be iterated over using nested loops, and the ‘AND’ operation is performed on the first element and result of equality between first and second element.
Below is a demonstration of the same −
Example
my_list = [(45, 67), (11, 23), (67, 45), (23, 11), (0, 9), (67, 45)] print("The list is : ") print(my_list) my_result = 0 for idx in range(0, len(my_list)): for iidx in range(idx + 1, len(my_list)): if my_list[iidx][0] == my_list[idx][1] and my_list[idx][1] == my_list[iidx][0]: my_result += 1 print("The count of bidirectional pairs are : ") print(my_result)
Output
The list is : [(45, 67), (11, 23), (67, 45), (23, 11), (0, 9), (67, 45)] The count of bidirectional pairs are : 3
Explanation
A list of tuples is defined, and is displayed on the console.
A result variable is assigned to 0.
The list is iterated over twice.
The ‘AND’ operation is performed between two elements.
The first element and the result of equality check between second and first elements.
Now, the result variable is incremented.
This result is displayed on the console.
Advertisements