📜  python list INTERSECTION - Python (1)

📅  最后修改于: 2023-12-03 15:18:56.331000             🧑  作者: Mango

Python List Intersection

Python provides us with several built-in methods to operate on lists. One such method is the intersection method which is used to find the common elements between two or more lists.

Syntax

The syntax for the intersection method is as follows:

list1.intersection(list2, list3, ..., listN)

Here, list1 is the first list and list2 to listN are the subsequent lists.

Example

Consider the following example:

fruits1 = ["apple", "banana", "orange", "peach"]
fruits2 = ["pear", "banana", "kiwi", "orange"]
common_fruits = fruits1.intersection(fruits2)
print(common_fruits)

In this example, we have two lists fruits1 and fruits2. We want to find the common elements between these two lists. To achieve this, we use the intersection method and pass fruits2 as an argument. The intersection method returns a new set with the common elements between the two lists, in this case, {"banana", "orange"}.

Notes
  • The intersection method only works for sets. However, you can convert a list to a set using the set() function.
  • The intersection method is case-sensitive. This means that {"apple"} and {"Apple"} are not considered equal.
  • The intersection method returns a set, not a list. If you need the result as a list, you can convert the set to a list using the list() function.
Conclusion

The intersection method is a useful tool to find the common elements between two or more lists. It can be very helpful when dealing with data analysis and manipulation tasks in Python.