Home > database >  How to sum even numbers from a list and then remove them?
How to sum even numbers from a list and then remove them?

Time:04-15

I have tried to add sum of even numbers of a list and I am successful but in my second part I am not able to delete even numbers from the list. For example my input is [1,2,4,6,5] and When I tried this given code below, the output for sum of even numbers was 8 and new list was [1,4,5]. I want output as sum of even numbers as 12 and new list is [1,5].

n=list(map(int, input("elements of array:-").strip().split()))
even_sum = 0 
for num in n:
    if num%2==0:
        even_sum  = num
        n.remove(num)
    else:
        odd_sum  = num
print(even_sum)
print(n)

CodePudding user response:

Here is a slightly more pythonic way to achieve what you want:

L = [1,2,4,6,5]
Lsum = sum([int(elem % 2 == 0) * elem for elem in L])
Lnew = [elem for elem in L if elem % 2 == 1]

CodePudding user response:

You shouldn't iterate over the list and modify it.

n = [1,2,4,6,5]
odd_list = []
even_sum = 0 
for num in n:
    if num%2==0:
        even_sum  = num
    else:
        odd_sum  = num
        odd_list.append(num)

Heres a more nicer way achieving that only. It is called list comprehension

n = [1, 2, 4, 6, 5]
even_list = [i for i in n if i%2==0]
even_sum = sum(even_list)

// The OP wants an odd list as a result, revised version:

n = [1, 2, 4, 6, 5]
odd_list = [i for i in n if i%2==1]
even_sum = sum(n) - sum(odd_list)

CodePudding user response:

This is happening because during iteration you are skipping some of the elements by removing others from the same sequence...

You can iterate backwards through the list instead. This eliminates the need for copying elements to a new list.

Like this:

n=list(map(int, input("elements of array:-").strip().split()))
i = len(n) -1
while i >= 0:
    if n[i] % 2 == 0:
        even_sum  = n[i]
        del n[i]
    else:
        odd_sum  = n[i]
    i -= 1
  • Related