How do I add numbers in a list that do not equal parameters?
<p>I am trying to write a function that will add all of the numbers in a list that do not equal the parameters.  The code I have, that is not working, is:</p>

<pre><code>def suminout(nums,a,b):
    total=0
    for i in range(len(nums)):
        if nums[i]!=a or nums[i]!=b:
            total=total+nums[i]
    return total
</code></pre>

<p>It appears to be summing everything in the list.</p>

<p>For example, if I called:
suminout([1,2,3,4],1,2)
it should return 7.  However, I am getting 10.</p>

<p>Any thoughts?</p>

<p>You need to use <code>and</code> instead of <code>or</code>.</p>

<pre><code>def suminout(nums,a,b):
    total=0
    for i in range(len(nums)):
        if nums[i]!=a and nums[i]!=b:
            total=total+nums[i]
    return total
</code></pre>

<p>Your <code>for</code> logic could be further simplified (without using <code>len()</code> and <code>range()</code>) as:</p>

<pre><code>for num in nums:
    if num not in [a, b]:  # same as: num != a and num != b
        total += num  # same as: total = total + num
</code></pre>

<p>Better way to achieve it using <code>list comprehension</code> with <code>sum()</code> as mentioned by Sean. OR you may use <a href="https://docs.python.org/2/library/functions.html#filter" rel="nofollow"><code>filter()</code></a> instead of list comprehension:</p>

<pre><code>&gt;&gt;&gt; my_list = [1, 2, 3, 4]
&gt;&gt;&gt; sum(filter(lambda x: x !=1 and x!=4, my_list))
5
</code></pre>

python list parameters sum