0

I have two lists, l1 and l2. l1 is a list of many numbers separated by commas. l2 has a section of l1.

l1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
l2 = [6, 7, 8, 9, 10]

I want l1 to become l1 = [1, 2, 3, 4, 5] by directly removing l2 from l1

Can I do that without While XXX:, For I in XXX:, and Recursions?

2 Answers2

2

You can if you convert the lists into sets. You can also use list comprehension.

l1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
l2 = [6, 7, 8, 9, 10]

# using sets and the difference operator
l3 = list(set(l1) - set(l2))

# or using list comprehension
l3 = [i for i in l1 if i not in l2]

There is also the builtin function filter and the itertools version filterfalse, these are not as preferred since they are less readable however

l3 = list(filter(lambda x: x not in l2, l1))

import itertools

l3 = list(itertools.filterfalse(lambda x: x in l2, l1))
Alexander
  • 16,091
  • 5
  • 13
  • 29
  • 1
    It's worth noting that using `set`s isn't guaranteed to preserve order. In this example, order just happens to be preserved when I run it, but I think it's a quirk of the CPython implementation. If I swap the ints for strs, order is not preserved. – wjandrea Aug 21 '22 at 23:34
0

You can use this simple line of code to do that

b2 = list(filter(lambda num: num not in l2, l1))

You need to know the filter function iterate over the array.

  • 2
    Don't use `list(filter(lambda))`. It's much more readable to use a list comprehension. See [Alexander's answer](/a/73438864/4518341). – wjandrea Aug 21 '22 at 23:22