Write a Python program to count integer in a given mixed list.
Original list:
[1, 'abcd', 3, 1.2, 4, 'xyz', 5, 'pqr', 7, -5, -12.22]
Version 1:
lst = [1, 'abcd', 3, 1.2, 4, 'xyz', 5, 'pqr', 7, -5, -12.22]
count_int = 0
for element in lst:
print(type(element))
if type(element) == int:
count_int += 1
print(count_int)
INPUT:
[1, 'abcd', 3, 1.2, 4, 'xyz', 5, 'pqr', 7, -5, -12.22]
OUTPUT:
6
Version 2:
lst = [1, 'abcd', 3, 1.2, 4, 'xyz', 5, 'pqr', 7, -5, -12.22]
print(len([x for x in lst if type(x) == int]))
6
P.S. if you need sum integer in a given mixed list:
lst = [1, 'abcd', 3, 1.2, 4, 'xyz', 5, 'pqr', 7, -5, -12.22]
print(sum([x for x in lst if type(x) == int]))
Comments
Leave a comment