Open In App

Python | Multiply Integer in Mixed List of string and numbers

Improve
Improve
Like Article
Like
Save
Share
Report

Sometimes, while working with Python, we can come across a problem in which we require to find the product of list. This problem is easier to solve. But this can get complex in case we have a mixture of data types to go along with it. Let’s discuss certain ways in which this task can be performed. 

Method #1: 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 to the product and hence can solve the problem. 

Approach:

  1. Initialize the list “test_list” with multiple data types including integers, strings, and tuples.
  2. Print the original list using the “print()” function and concatenating it with a string using the “+” operator.
  3. Initialize the variable “res” to 1, which will be used to store the product of all integers present in the list.
  4. Using a “for” loop, iterate over each element of the “test_list”.
  5. Within the loop, try to convert each element to an integer using the “int()” function.
  6. If the conversion is successful, multiply the integer with the value of the “res” variable and update the value of the “res” variable with the result.
  7. If the conversion is not successful, i.e., if the element is not an integer, simply ignore the element using the “pass” statement.
  8. After the loop ends, print the product of all integers present in the list using the “print()” function and concatenate it with a string using the “+” operator.

Python3




# Python3 code to demonstrate working of
# Mixed List Integer Multiplication
# using type caste and exception handling
 
# initializing list
test_list = [5, 8, "gfg", 8, (5, 7), 'is', 2]
 
# printing original list
print("The original list is : " + str(test_list))
 
# Mixed List Integer Multiplication
# using type caste and exception handling
res = 1
for ele in test_list:
    try:
        res *= int(ele)
    except:
        pass
 
# printing result
print("Product of integers in list : " + str(res))


Output

The original list is : [5, 8, 'gfg', 8, (5, 7), 'is', 2]
Product of integers in list : 640

Time complexity: O(n), where n is the number of elements in the list.
Auxiliary space: O(1), as we only need to store the integer result in the ‘res’ variable.

Method #2: Using loop + isinstance()

This is a brute force way in which this task can be performed. In this, we run a loop over all the elements and perform multiplication only when we find an integer using isinstance(). 

Python3




# Python3 code to demonstrate working of
# Mixed List Integer Multiplication
# using loop + isinstance()
 
# initializing list
test_list = [5, 8, "gfg", 8, (5, 7), 'is', 2]
 
# printing original list
print("The original list is : " + str(test_list))
 
# Mixed List Integer Multiplication
# using loop + isinstance()
res = 1
for ele in test_list:
    if(isinstance(ele, int)):
        res *= ele
 
# printing result
print("Product of integers in list : " + str(res))


Output

The original list is : [5, 8, 'gfg', 8, (5, 7), 'is', 2]
Product of integers in list : 640

Time complexity: O(n), where n is the length of the input list.
Auxiliary space: O(1), as the algorithm only uses a constant amount of extra space regardless of the input size.

Method #3: Using loop and type() 

Python3




# Python3 code to demonstrate working of
# Mixed List Integer Multiplication
 
# initializing list
test_list = [5, 8, "gfg", 8, (5, 7), 'is', 2]
 
# printing original list
print("The original list is : " + str(test_list))
 
# Mixed List Integer Multiplication
res = 1
for ele in test_list:
    if(type(ele) is int):
        res *= ele
 
# printing result
print("Product of integers in list : " + str(res))


Output

The original list is : [5, 8, 'gfg', 8, (5, 7), 'is', 2]
Product of integers in list : 640

Time complexity: O(n), where n is the length of the input list.
Auxiliary space: O(1), as the algorithm only uses a constant amount of extra space regardless of the input size.

Method #4: Using filter() + map() + reduce()

We can use filter() function to filter out integers from the list, map() function to convert them to integers and reduce() function to get the product of all integers in the list.

Python3




# Python3 code to demonstrate working of
# Mixed List Integer Multiplication
# using filter() + map() + reduce()
 
import operator
from functools import reduce
 
# initializing list
test_list = [5, 8, "gfg", 8, (5, 7), 'is', 2]
 
# printing original list
print("The original list is : " + str(test_list))
 
# Mixed List Integer Multiplication
# using filter() + map() + reduce()
 
#filter only integers using filter function
#convert filtered_list to list
#multiply all integers using reduce function
res = reduce(operator.mul, map(int, filter(lambda x: type(x) == int, test_list)))
 
# printing result
print("Product of integers in list : " + str(res))
 
#This code is contributed by Edula Vinay Kumar Reddy


Output

The original list is : [5, 8, 'gfg', 8, (5, 7), 'is', 2]
Product of integers in list : 640

Time complexity : O(n)
Auxiliary Space : O(n)

Method#5: Using Recursive method.

Step-by-step approach:

  • Define a recursive function product_of_integers that takes a list as input.
  • If the list is empty, return 1 (the identity element for multiplication).
  • If the first element of the list is an integer, recursively call product_of_integers with the rest of the list and multiply the first element with the result.
  • If the first element is not an integer, recursively call product_of_integers with the rest of the list.
  • Return the result of the recursive call.

Python3




def product_of_integers(lst):
    if not lst:
        return 1
    if isinstance(lst[0], int):
        return lst[0] * product_of_integers(lst[1:])
    else:
        return product_of_integers(lst[1:])
         
# initializing list
test_list = [5, 8, "gfg", 8, (5, 7), 'is', 2]
 
# printing original list
print("The original list is : " + str(test_list))
 
# Mixed List Integer Multiplication using recursion
res = product_of_integers(test_list)
 
# printing result
print("Product of integers in list : " + str(res))


Output

The original list is : [5, 8, 'gfg', 8, (5, 7), 'is', 2]
Product of integers in list : 640

Time complexity: O(n), where n is the length of the input list. The function needs to process each element of the list once.
Auxiliary Space: O(n), where n is the length of the input list. The function needs to keep track of the call stack for each recursive call.

Method #6: Using list comprehension and try-except block

Step-by-Step Approach:

  • Define a variable to store the product of integers initialized with 1.
  • Use list comprehension to filter out non-integer values from the list.
  • Use a for loop to iterate over the list of integers and multiply each integer to the variable defined in step 1.
  • Wrap the multiplication operation in a try-except block to catch any exceptions that might occur.
  • Return the result

Python3




def product_of_integers(lst):
    prod = 1
    lst_int = [x for x in lst if isinstance(x, int)]
    for num in lst_int:
        try:
            prod *= num
        except:
            pass
    return prod
         
test_list = [5, 8, "gfg", 8, (5, 7), 'is', 2]
res = product_of_integers(test_list)
print("Product of integers in list : " + str(res))


Output

Product of integers in list : 640

Time Complexity: O(n), where n is the length of the input list. The for loop iterates over the list once.
Auxiliary Space: O(n), where n is the length of the input list. A new list is created to contain only the integers.



Last Updated : 02 May, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads