Home > Software design >  Modification/creation of new lists
Modification/creation of new lists

Time:01-26

I have been tasked with finding the even numbers from this list and multiplying them all together. I have used modulus to find the evens, and have a way of multiplying a list, however I do not know how to place the even values found by the modulus into a new list to be modified.

Here is the list:

list3 = [146, 875, 911, 83, 81, 439, 44, 5, 46, 76, 61, 68, 1, 14, 38, 26, 21] 

and here is what I have for finding even:

for num in list3:
    if (num % 2 ==0):
print(even_list)

and I am using a multiplication function I created earlier:

def multiply_list(list1):
    result = 1
    for num in list1:
        result = result * num
    return result

Forgive me, I am sure this is an easy fix. I am very new to this.

CodePudding user response:

I am not sure if I understood your question properly. Below is the code to insert elements in the list.

list3 = [146, 875, 911, 83, 81, 439, 44, 5, 46, 76, 61, 68, 1, 14, 38, 26, 21]

even_list = []

for num in list3:
    if (num % 2 ==0):
        even_list.append(num)

print(even_list)

If you want to multiply the even elements in the list, use below code.

def evenList(list):
    even_list = []
    for num in list:
        if (num % 2 ==0):
            even_list.append(num)
            
    return even_list
            
def multiply_list(list1):
    result = 1

    for num in list1:
        result = result * num

    return result

list3 = [146, 875, 911, 83, 81, 439, 44, 5, 46, 76, 61, 68, 1, 14, 38, 26, 21]

print(multiply_list(evenList(list3)))

CodePudding user response:

The list of even numbers can be found by using a for loop, or a list comprehension for more concise syntax. Then use functools.reduce to multiply the elements together.

from functools import reduce

list3 = [146, 875, 911, 83, 81, 439, 44, 5, 46, 76, 61, 68, 1, 14, 38, 26, 21] 

even_list = [n for n in list3 if n % 2 == 0]
print(even_list)  # [146, 44, 46, 76, 68, 14, 38, 26]

even_product = reduce(lambda product, n: n*product, even_list)
print(even_product)  # 21123741743104
  • Related