Answer to Question #330032 in Python for Shubham Tiwari

Question #330032

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]


1
Expert's answer
2022-04-18T15:20:01-0400

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]))

OUTPUT:

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]))




Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS