Python | Multiply Integer in Mixed List of string and numbers
We are given a list containing mixed data types: integers, strings, and even tuples. Our task is to multiply the integers present in the list, while ignoring the non-integer elements and return the final result. For example, if we have a list like this: `[5, 8, "gfg", 8, (5, 7), 'is', 2]`, and we want to multiply the integers, the output will be `640`as product of (5, 8, 8, and 2) is 640.
Using Type casting + Exception Handling
We can employ a brute force method to type caste each element and catch the exception if any occurs. This can ensure that only integers are multiplied with the product and hence can solve the problem.
a = [5, 8, "gfg", 8, (5, 7), 'is', 2]
res = 1
for element in a:
try:
res *= int(element)
except:
pass
print(str(res))
Output
640
Explanation:
- Iterates through a mixed list, initializing res to 1.
- Uses a try-except block to convert elements to integers and multiply them.
- Ignores non-numeric values and prints the final product.
Using isinstance()
This brute-force approach multiplies only the integer elements in a mixed-data list by iterating through all elements and using isinstance() to filter integers before multiplying.
a = [5, 8, "gfg", 8, (5, 7), 'is', 2]
res = 1
for element in a:
if(isinstance(element, int)):
res *= element
print(str(res))
Output
640
Explanation: isinstance(element, int) method is used to filter elements that are of integer type.
Using type()
We can loop through the list and multiply only the elements that are of integer type using type().
a = [5, 8, "gfg", 8, (5, 7), 'is', 2]
res = 1
for element in a:
if(type(element) is int):
res *= element
print(str(res))
Output
640
Explanation: operation res *= element is executed only for integer elements.
Using math.prod()
Math library in python provides .prod() method which can be used to get the product of all the elements in the list.
import math
a = [5, 8, "gfg", 8, (5, 7), 'is', 2]
res = math.prod([x for x in a if isinstance(x, int)])
print(res)
Output
640
Explanation: math.prod() multiplies all elements in the filtered list.
Using reduce()
We can use reduce() to multiply elements from a filtered list that contains only integers. The function starts with 1 and multiplies each integer iteratively.
from functools import reduce
a = [5, 8, "gfg", 8, (5, 7), 'is', 2]
res = reduce(lambda x, y: x * y, [x for x in a if isinstance(x, int)], 1)
print(res)
Output
640
Explanation: list comprehension [x for x in a if isinstance(x, int)] extracts integers and then reduce(lambda x, y: x * y, [...], 1) starts with 1 and multiplies all elements in the list.