Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python to Find number of lists in a tuple
A Python tuple is ordered and unchangeable. It can contain lists as its elements. Given a tuple made up of lists, let's find out how many lists are present in the tuple using different approaches.
Using len() Function
The simplest approach is to use the built-in len() function, which returns the count of elements (lists) in the tuple ?
tupA = (['a', 'b', 'x'], [21, 19])
tupB = (['n', 'm'], ['z', 'y', 'x'], [3, 7, 89])
print("The number of lists in tupA:", len(tupA))
print("The number of lists in tupB:", len(tupB))
The output of the above code is ?
The number of lists in tupA: 2 The number of lists in tupB: 3
Using a User-Defined Function
For reusable code, we can create a function that validates the input and counts the lists ?
tupA = (['a', 'b', 'x'], [21, 19])
tupB = (['n', 'm'], ['z', 'y', 'x'], [3, 7, 89])
def count_lists(input_tuple):
if isinstance(input_tuple, tuple):
return len(input_tuple)
else:
return "Input is not a tuple"
print("The number of lists in tupA:", count_lists(tupA))
print("The number of lists in tupB:", count_lists(tupB))
The output of the above code is ?
The number of lists in tupA: 2 The number of lists in tupB: 3
Counting Only List Elements
If the tuple contains mixed data types and you only want to count actual list elements ?
mixed_tuple = (['a', 'b'], 42, ['x', 'y'], "hello", [1, 2, 3])
def count_only_lists(input_tuple):
return sum(1 for item in input_tuple if isinstance(item, list))
print("Total elements:", len(mixed_tuple))
print("Only list elements:", count_only_lists(mixed_tuple))
The output of the above code is ?
Total elements: 5 Only list elements: 3
Comparison
| Method | Use Case | Advantage |
|---|---|---|
len() |
All elements are lists | Simple and fast |
| User-defined function | Input validation needed | Reusable and safe |
| Type checking | Mixed data types | Counts only lists |
Conclusion
Use len() for simple counting when all tuple elements are lists. For mixed data types or input validation, create a function with type checking to count only list elements accurately.
