diff --git a/README.md b/README.md index da3cfd516..93d7deb2d 100644 --- a/README.md +++ b/README.md @@ -661,12 +661,12 @@ initialize_list_with_values(5, 2) # [2, 2, 2, 2, 2] 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 def intersection(a, b): - _b = set(b) - return [item for item in a if item in _b] + _a, _b = set(a), set(b) + return list(_a & _b) ```
diff --git a/snippet_data/snippetList.json b/snippet_data/snippetList.json index db3d4e8cb..0969948a0 100644 --- a/snippet_data/snippetList.json +++ b/snippet_data/snippetList.json @@ -558,14 +558,14 @@ "type": "snippetListing", "title": "intersection", "attributes": { - "text": "Returns a list of elements that exist in both lists.\n\nCreate a `set` from `b`, then use list comprehension on `a` to only keep values contained in both lists.\n\n", + "text": "Returns a list of elements that exist in both lists.\n\nCreate 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`.\n\n", "tags": [ "list", "beginner" ] }, "meta": { - "hash": "a332cce7b7d7e303469e8c39c4926bf92ecb12847c3932985cc633e3a85a23bb" + "hash": "d20f757b18d4368324bfa74bb907f5dc2df9262886ea3722edd5015418ce282d" } }, { diff --git a/snippet_data/snippets.json b/snippet_data/snippets.json index 9550b72ed..a78443343 100644 --- a/snippet_data/snippets.json +++ b/snippet_data/snippets.json @@ -739,9 +739,9 @@ "type": "snippet", "attributes": { "fileName": "intersection.md", - "text": "Returns a list of elements that exist in both lists.\n\nCreate a `set` from `b`, then use list comprehension on `a` to only keep values contained in both lists.\n\n", + "text": "Returns a list of elements that exist in both lists.\n\nCreate 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`.\n\n", "codeBlocks": { - "code": "def intersection(a, b):\n _b = set(b)\n return [item for item in a if item in _b]", + "code": "def intersection(a, b):\n _a, _b = set(a), set(b)\n return list(_a & _b)", "example": "intersection([1, 2, 3], [4, 3, 2]) # [2, 3]" }, "tags": [ @@ -750,7 +750,7 @@ ] }, "meta": { - "hash": "a332cce7b7d7e303469e8c39c4926bf92ecb12847c3932985cc633e3a85a23bb" + "hash": "d20f757b18d4368324bfa74bb907f5dc2df9262886ea3722edd5015418ce282d" } }, {