update intersection snippet

This commit is contained in:
Juliano Garcia
2019-10-02 11:25:24 -03:00
parent 9768c5d510
commit 20a462d32f

View File

@ -5,12 +5,12 @@ tags: list,beginner
Returns a list of elements that exist in both lists. Returns a list of elements that exist in both lists.
Create a `set` from `b`, then use list comprehension on `a` to only keep values contained in both lists. Create a `set` from `a` and `b`, then use the built-in set operator `&` to only keep values contained in both sets, then transform the `set` back into a `list`.
```py ```py
def intersection(a, b): def intersection(a, b):
_b = set(b) _a, _b = set(a), set(b)
return [item for item in a if item in _b] return list(_a & _b)
``` ```
```py ```py