The intersection of two lists is the items that appear in both. Here we find the people who are members of both clubs.
The program
python
python_club = ["Ada", "Linus", "Grace", "Alan"] chess_club = ["Hedy", "Grace", "Ada", "Margaret"] chess_members = set(chess_club) both = [name for name in python_club if name in chess_members] print("In both clubs:", both)
output
In both clubs: ['Ada', 'Grace']
How it works
- The list comprehension keeps each name from
python_clubthat is also in the chess club, so the result is in the order of the first list. set(chess_club)is made once, before the loop. Checkinginon a set is fast, even for a big set. Checkinginon a list looks at the items one by one, which gets slow when both lists are long.
Another way: the & operator
If you do not need the order, turn both lists into sets and use &:
python
a = [1, 2, 3, 4, 5, 5] b = [5, 3, 7, 4, 6] common = set(a) & set(b) print(sorted(common))
output
[3, 4, 5]
- A set has no duplicates, so 5 appears once even though it is twice in
a. - A set has no fixed order. For strings, the order can even change each time you run the program.
sorted()gives a list in a predictable order.
Related programs: Set operations.