Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does filter,map, and reduce in Python create a new copy of list?

Using Python 2.7. Let us say we have list_of_nums = [1,2,2,3,4,5] and we want to remove all occurrences of 2. We can achieve it by list_of_nums[:] = filter(lambda x: x! = 2, list_of_nums) or list_of_nums = filter(lambda x: x! = 2, list_of_nums).

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

like image 921
malhar Avatar asked Sep 03 '16 15:09

malhar


1 Answers

list_of_nums[:] = filter(lambda x: x != 2, list_of_nums)

and

list_of_nums = filter(lambda x: x != 2, list_of_nums)

are two different operations that end up with mostly the same result.

In both cases,

filter(lambda x: x != 2, list_of_nums)

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

The first case,

list_of_nums[:] = filter(lambda x: x != 2, list_of_nums)

then deletes all items from list_of_nums and replaces them with the items from the new list or iterable.

The second case,

list_of_nums = filter(lambda x: x != 2, list_of_nums)

assigns the new list to the variable list_of_nums.

The time when this makes a difference is this:

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)

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

like image 136
J Earls Avatar answered Sep 23 '22 15:09

J Earls