Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Use a Set to Find the Intersection of Two Lists

Python Use a Set to Find the Intersection of Two Lists

Document Object Reference Manual Python3 Examples

In Python, a set is an unordered and non-repeating data structure. We can use the characteristics of sets to find the intersection of two lists. The intersection refers to the elements that exist in both lists.

Example

list1

=

[

1

,

2

,

3

,

4

,

5

]

list2

=

[

4

,

5

,

6

,

7

,

8

]

Convert the list to a set

set1

=

set

(

list1

)

set2

=

set

(

list2

)

Use the set intersection operation

intersection

=

set1 &

;

set2

Convert the result back to a list

result

=

list

(

intersection

)

print

(

result

)

Code analysis:

  1. list1 and list2 are two lists containing integers.
  2. set(list1) and set(list2) Convert the list to a set, which removes duplicate elements and facilitates set operations.
  3. set1 & set2 Use the set intersection operator & to find elements that exist in both sets.
  4. list(intersection) Convert the result back to list form for output.
  5. print(result) Output the final intersection result.

Output result:

[4, 5]

Document Object Reference Manual Python3 Examples