
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Count the elements till first tuple in Python
When it is required to count the elements up to the first tuple, a simple loop, the 'isinstance' method, and the 'enumerate' method can be used.
Below is a demonstration of the same −
Example
my_tuple_1 = (7, 8, 11, 0 ,(3, 4, 3), (2, 22)) print ("The tuple is : " ) print(my_tuple_1) for count, elem in enumerate(my_tuple_1): if isinstance(elem, tuple): break print("The number of elements up to the first tuple are : ") print(count)
Output
The tuple is : (7, 8, 11, 0, (3, 4, 3), (2, 22)) The number of elements up to the first tuple are : 4
Explanation
- A nested tuple is defined and is displayed on the console.
- The tuple is enumerated, and iterated over.
- The isinstance method is used to check if the element in the tuple belongs to a certain type.
- This result is stored in a counter since 'enumerate' was used.
- It is displayed as output on the console.
- Related Articles
- Count occurrence of all elements of list in a tuple in Python
- How to group Python tuple elements by their first element?
- Python program to get first and last elements from a tuple
- Delete Tuple Elements in Python
- Python program to count the elements in a list until an element is a Tuple?
- Modulo of tuple elements in Python
- How to append elements in Python tuple?
- Python - Join tuple elements in a list
- Python – Concatenate Rear elements in Tuple List
- Finding unique elements from Tuple in Python
- Raise elements of tuple as power to another tuple in Python
- Python program to count Bidirectional Tuple Pairs
- Python - Unique keys count for Value in Tuple List
- Python Program to Replace Elements in a Tuple
- Get first index values in tuple of strings in Python

Advertisements