-2

Question

Can List.remove not be used as the function to apply in the map(function, iterable, ...) builtin?

%%timeit
import random
m = _max = 10000
n = random.randint(1, m)

outer = random.sample(population=range(1, 2*n+1), k=2*n)
inner = random.sample(population=range(1, n+1), k=n)
print(f"outer is {outer}")
print(f"inner is {inner}")

# 622 ms ± 216 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
# [o for o in outer if o not in inner]

# 347 ms ± 139 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
for i in inner:
    outer.remove(i)
print(outer)
---

outer is [16, 5, 9, 2, 8, 12, 1, 4, 7, 13, 14, 10, 3, 15, 6, 11]
inner is [4, 1, 5, 8, 6, 7, 2, 3]
[16, 9, 12, 13, 14, 10, 15, 11]

I thought it was applicable with the map but it returned a list of None. Please advise if it can be applied in some way, or the reason not applicable. Please point out if I made a mistake.

#%%timeit
import random
m = _max = 10000
n = random.randint(1, m)

outer = random.sample(population=range(1, 2*n+1), k=2*n)
inner = random.sample(population=range(1, n+1), k=n)
print(f"outer is {outer}")
print(f"inner is {inner}")

print(outer.remove)
print(list(map(outer.remove, inner)))
---

outer is [11, 3, 1, 5, 12, 9, 8, 4, 10, 6, 7, 2]
inner is [1, 3, 4, 6, 5, 2]
<built-in method remove of list object at 0x7f470b6fbd00>
[None, None, None, None, None, None]
mon
  • 18,789
  • 22
  • 112
  • 205
  • 3
    It works as expected. `remove` affects the initial list but returns nothing (`None`). Print `outer` again and it should be shorter. – Guimoute Jan 25 '21 at 23:36
  • 1
    @Guimoute, please add that in the answer section. This is a straight forward answer – Joe Ferndz Jan 25 '21 at 23:53

2 Answers2

1

It works as expected. remove affects the initial list but returns nothing (None). Print outer again and it should be shorter.

Guimoute
  • 4,407
  • 3
  • 12
  • 28
0

Actually it works as desired. The remove function affects the initial list but its return value is None. Simply Print outer again and it will be shorter!

Bialomazur
  • 1,122
  • 2
  • 7
  • 18