diff --git a/snippets/difference.md b/snippets/difference.md index 4c730cf68..2391a9837 100644 --- a/snippets/difference.md +++ b/snippets/difference.md @@ -5,7 +5,7 @@ tags: list,beginner 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 def difference(a, b): diff --git a/snippets/intersection.md b/snippets/intersection.md new file mode 100644 index 000000000..5fd30d874 --- /dev/null +++ b/snippets/intersection.md @@ -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] +```