Add intersection snippet

This commit is contained in:
Angelos Chalaris
2019-08-20 15:14:26 +03:00
parent 7ebb059255
commit 5df7886a80
2 changed files with 19 additions and 1 deletions

18
snippets/intersection.md Normal file
View 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]
```