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?
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]
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With