user2581724
user2581724

Reputation: 245

How do I sum a list of numbers while ignoring duplicate numbers?

I need help trying to sum up numbers in a list while ignoring duplicates. Let's say I have a list [1, 2, 2, 3, 3, 3] the answer should be 6 because 1 + 2 + 3 = 6. The extra 2 and extra 3s should not be included in the calculation.

def sumOfUniqueNums(list):

    sum = 0

    list1 = [1, 2, 2, 3, 3, 3]
    remove = []
    [remove.append(i) for i in list1 if i not in remove]

    sum(list1)

    return sum

Updated function

def sumOfUniqueNums(numbers):
    return sum(set(numbers))

Upvotes: 0

Views: 1553

Answers (2)

kojiro
kojiro

Reputation: 77137

A set cannot contain duplicate values, so it's as simple as

sum(set(list1))

Python will let you override built-in names, though, so you'll need to unassign sum before this will work.

Upvotes: 4

Sharif Mamun
Sharif Mamun

Reputation: 3554

Try this, should work fine:

def sumOfUniqueNums(values):
    return sum(set(values))

print sumOfUniqueNums([1,1,2,2])
3

print sumOfUniqueNums([1,1,2,2,3])
6

Upvotes: 0

Related Questions