Add intersection snippet
This commit is contained in:
@ -5,7 +5,7 @@ tags: list,beginner
|
|||||||
|
|
||||||
Returns the difference between two iterables.
|
Returns the difference between two iterables.
|
||||||
|
|
||||||
Create a `set` fromn `b`, then use list comprehension on `a` to only keep values not contained in the previously created set, `_b`.
|
Create a `set` from `b`, then use list comprehension on `a` to only keep values not contained in the previously created set, `_b`.
|
||||||
|
|
||||||
```py
|
```py
|
||||||
def difference(a, b):
|
def difference(a, b):
|
||||||
|
|||||||
18
snippets/intersection.md
Normal file
18
snippets/intersection.md
Normal file
@ -0,0 +1,18 @@
|
|||||||
|
---
|
||||||
|
title: intersection
|
||||||
|
tags: list,beginner
|
||||||
|
---
|
||||||
|
|
||||||
|
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.
|
||||||
|
|
||||||
|
```py
|
||||||
|
def intersection(a, b):
|
||||||
|
_b = set(b)
|
||||||
|
return [item for item in a if item in _b]
|
||||||
|
```
|
||||||
|
|
||||||
|
```py
|
||||||
|
intersection([1, 2, 3], [4, 3, 2]) # [2, 3]
|
||||||
|
```
|
||||||
Reference in New Issue
Block a user