
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Count Elements in a List Until an Element is a Tuple in Python
In this article, we will count the elements in a list until an element is a Tuple.
The list is the most versatile datatype available in Python, which can be written as a list of commaseparated values (items) between square brackets. Important thing about a list is that the items in a list need not be of the same type. A tuple is a sequence of immutable Python objects. Tuples are sequences, just like lists. The main difference between the tuples and the lists is that the tuples cannot be changed unlike lists. Tuples use parentheses, whereas lists use square brackets.
Let's say we have the following List and within that we have a Tuple as well ?
mylist = [25, 50, 75, 100, 125, (20, 175, 100, 87), 500]
The output should be ?
List = [25, 50, 75, 100, 125, (20, 175, 100, 87), 500] List Length = 7
Count the elements in a list until an element is a Tuple using isinstance()
Use the isinstance() method to count the elements in a list until an element is a Tuple ?
Example
def countFunc(k): c = 0 for i in k: if isinstance(i, tuple): break c = c + 1 return c # Driver Code mylist = [25, 50, 75, 100, 125, (20, 175, 100, 87), 500] print("List with Tuple = ",mylist) print("Count of elements in a list until an element is a Tuple = ",countFunc(mylist))
Output
List with Tuple = [25, 50, 75, 100, 125, (20, 175, 100, 87), 500] Count of elements in a list until an element is a Tuple = 5
Count the elements in a list until an element is a Tuple using type()
Use the type() method to count the elements in a list until an element is a Tuple ?
Example
def countFunc(k): c = 0 for i in k: if type(i) is tuple: break c = c + 1 return c # Driver Code mylist = [25, 50, 75, 100, 125, (20, 175, 100, 87), 500] print("List with Tuple = ",mylist) print("Count of elements in a list until an element is a Tuple = ",countFunc(mylist))
Output
List with Tuple = [25, 50, 75, 100, 125, (20, 175, 100, 87), 500] Count of elements in a list until an element is a Tuple = 5