Does filter,map, and reduce in Python create a new copy of list?
<p>Using <code>Python 2.7</code>. Let us say we have <code>list_of_nums = [1,2,2,3,4,5]</code>
and we want to remove all occurrences of 2. We can achieve it by
<code>list_of_nums[:] = filter(lambda x: x! = 2, list_of_nums)</code> or  <code>list_of_nums = filter(lambda x: x! = 2, list_of_nums)</code>.</p>

<p>Is this an "in-place" substitution? Also, are we creating a copy of list when we use filter?</p>

<pre><code>list_of_nums[:] = filter(lambda x: x != 2, list_of_nums)
</code></pre>

<p>and</p>

<pre><code>list_of_nums = filter(lambda x: x != 2, list_of_nums)
</code></pre>

<p>are two different operations that end up with <em>mostly</em> the same result.</p>

<p>In both cases,</p>

<pre><code>filter(lambda x: x != 2, list_of_nums)
</code></pre>

<p>returns either a new list containing items that match the filter (in Python 2), or an iterable over <code>list_of_nums</code> that returns the same items (in Python 3).</p>

<p>The first case,</p>

<pre><code>list_of_nums[:] = filter(lambda x: x != 2, list_of_nums)
</code></pre>

<p>then deletes all items from <code>list_of_nums</code> and replaces them with the items from the new list or iterable.</p>

<p>The second case,</p>

<pre><code>list_of_nums = filter(lambda x: x != 2, list_of_nums)
</code></pre>

<p>assigns the new list to the variable <code>list_of_nums</code>.</p>

<p>The time when this makes a difference is this:</p>

<pre><code>def processItemsNotTwo_case1(list_of_nums):
    list_of_nums[:] = filter(lambda x: x != 2, list_of_nums)
    # do stuff here
    # return something

def processItemsNotTwo_case2(list_of_nums):
    list_of_nums = filter(lambda x: x != 2, list_of_nums)
    # do stuff here
    # return something

list1 = [1,2,2,3,4,5]
processItemsNotTwo_case1(list1)
list2 = [1,2,2,3,4,5]
processItemsNotTwo_case2(list2)
</code></pre>

<p>With this code, <code>list1</code> ends up with the new contents <code>[1,3,4,5]</code>, whereas <code>list2</code> ends up with the original contents <code>[1,2,2,3,4,5]</code>.</p>

python python-2.7 lambda higher-order-functions