Python | Integer count in Mixed List
Last Updated :
11 May, 2023
The lists in python can handle different type of data types in it. The manipulation of such lists is complicated. Sometimes we have a problem in which we need to find the count of integer values in which the list can contain string as a data type i.e heterogeneous. Let’s discuss certain ways in which this can be performed.
Method #1 : Using list comprehension + len() + isinstance()
This particular problem can be solved by filtering our search of len using the isinstance method, we can filter out the integer value and then can use len function to get required length value.
Python3
# Python3 code to demonstrate
# Integer count in Mixed List
# using list comprehension + len() + isinstance()
# initializing list
test_list = [3, 'computer', 5, 'geeks', 6, 7]
# printing original list
print ("The original list is : " + str(test_list))
# using list comprehension + len() + isinstance()
# Integer count in Mixed List
res = len(list(i for i in test_list if isinstance(i, int)))
# printing result
print ("The length of integers in list is : " + str(res))
OutputThe original list is : [3, 'computer', 5, 'geeks', 6, 7]
The length of integers in list is : 4
The time complexity of the above program is O(n), where n is the length of the input list.
The space complexity of the program is O(1), which is constant. This is because only a few variables are used to store the input list.
Method #2 : Using lambda + map() + len() + isinstance()
The above problem can also be solved using the lambda function as a map() in the len() along with the isinstance method which performs the task of checking for integer values.
Python3
# Python3 code to demonstrate
# Integer count in Mixed List
# using lambda + map() + len() + isinstance()
# initializing list
test_list = [3, 'computer', 5, 'geeks', 6, 7]
# printing original list
print ("The original list is : " + str(test_list))
# using lambda + map() + len() + isinstance()
# Integer count in Mixed List
temp = list(map(lambda i: isinstance(i, int), test_list))
res = len([ele for ele in temp if ele])
# printing result
print ("The length of integers in list is : " + str(res))
OutputThe original list is : [3, 'computer', 5, 'geeks', 6, 7]
The length of integers in list is : 4
Time Complexity: O(n), where n is the length of the list test_list
Auxiliary Space: O(1) additional space is not needed
Method #3 : Using type() and len() methods
The above problem can be solved by using type() to check if the type of the element as int, then append that item in a new list and print the size of the new list.
Python3
# Python3 code to demonstrate
# Integer count in Mixed List
# initializing list
test_list = [3, 'computer', 5, 'geeks', 6, 7]
# printing original list
print("The original list is : " + str(test_list))
# Integer count in Mixed List
res = []
for i in test_list:
if(type(i) is int):
res.append(i)
x = len(res)
# printing result
print("The length of integers in list is : " + str(x))
OutputThe original list is : [3, 'computer', 5, 'geeks', 6, 7]
The length of integers in list is : 4
Time Complexity: O(n*n), where n is the number of elements in the list “test_list”.
Auxiliary Space: O(n), where n is the number of elements in the list “test_list”.
Method #4: Using filter() and len() method
This approach is similar to method 1, but instead of using list comprehension, we use filter() function to filter out the integers.
Python3
# Python3 code to demonstrate
# Integer count in Mixed List
def is_int(val):
return isinstance(val, int)
# initializing list
test_list = [3, 'computer', 5, 'geeks', 6, 7]
# printing original list
print("The original list is : " + str(test_list))
res = len(list(filter(is_int, test_list)))
# printing result
print("The length of integers in list is : " + str(res))
OutputThe original list is : [3, 'computer', 5, 'geeks', 6, 7]
The length of integers in list is : 4
Time Complexity: O(n) where n is the number of elements in the list
Auxiliary Space: O(n) where n is the number of integers in the list
Method #4: Using try and except method.
Algorithm:
- Initialize a counter variable res to zero.
- Loop through each item i in the list test_list.
- For each item i, check if its type is int.
- If i is of type int, increment the counter variable res.
- Finally, print out the value of the counter variable res as the length of integers in the list.
Python3
test_list = [3, 'computer', 5, 'geeks', 6, 7]
try:
res = 0
for i in test_list:
if type(i) == int:
res += 1
print("The length of integers in list is : " + str(res))
except Exception as e:
print("An error occurred: " + str(e))
OutputThe length of integers in list is : 4
Time complexity:
The time complexity of this algorithm is O(n), where n is the length of the input list test_list. This is because the algorithm needs to loop through each item in the list once in order to count the number of integers in the list.
Auxiliary Space:
The auxiliary space complexity of this algorithm is O(1) because it only uses a constant amount of additional space to store the counter variable res and the loop variable i. No additional data structures are used to store the input list or the intermediate results, so the space complexity is constant with respect to the input size.
Method #5: Using isdigit()
Approach:
- Initialize a variable count to 0.
- Loop through the elements in the list using a for loop.
- Check if the element is a digit or not using the isdigit() method.
- If the element is a digit, increment the count variable by 1.
- Return the count variable after the loop ends.
Python3
# Initialize the list
lst = [3, 'computer', 5, 'geeks', 6, 7]
# print the list
print("The original list is: ",lst)
count = 0
for elem in lst:
if str(elem).isdigit():
count += 1
# printing result
print("The length of integers in list is :", count)
OutputThe original list is: [3, 'computer', 5, 'geeks', 6, 7]
The length of integers in list is : 4
Time complexity: O(n), where n is the length of the input list.
Space complexity: O(1)
Similar Reads
Python Tutorial | Learn Python Programming Language Python Tutorial â Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly.Python is:A high-level language, used in web development, data science, automatio
10 min read
Python Interview Questions and Answers Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Enumerate() in Python enumerate() function adds a counter to each item in a list or other iterable. It turns the iterable into something we can loop through, where each item comes with its number (starting from 0 by default). We can also turn it into a list of (number, item) pairs using list().Let's look at a simple exam
3 min read
Python Data Types Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
9 min read
Python Introduction Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien
3 min read
Input and Output in Python Understanding input and output operations is fundamental to Python programming. With the print() function, we can display output in various formats, while the input() function enables interaction with users by gathering input during program execution. Taking input in PythonPython input() function is
8 min read