Multiple ways to do python Intersection list example
This tutorials explains about intersection of two lists. Intersection means an returns list of element, where each element exists in two lists. It is an alias overlap or common elements in both list.
For example, two list contains following data
list1 = [11,12,13,14,5,9,20]
list2 = [1,2,11,9,20]
Intersection
of list1 and list2 is [11,9,20]
Python Intersection lists example
Multiple ways we can do
- using for in list
It is an native way of doing
- Iterate an each element in a list1
- Check element exists in list2, if exists, append to an list
list1 = [11,12,13,14,5,9,20]
list2 = [1,2,11,9,20]
result = [val for val in list1 if val in list2]
print(result)# [11, 9, 20]
Let’s see if there is an duplicate element in the list.
list1 contains 11 elements repeated twice.
list1 = [11,12,13,14,5,9,11,20]
list2 = [1,2,11,9,20]
result = [val for val in list1 if val in list2]
print(result)
Pros: Order of an element are preseved
Cons:
- Time complexity is o(n*2)
- Duplicate elements returned if exists
Second #2 using set
- Convert the list into set using
set(list)
constructor - Join the two sets using & operator, returns set of common elements
- Again Convert to list using
list(set)
constructor
Here is an example
list1 = [11,12,13,14,5,9,20]
list2 = [1,2,11,9,20]
result=list(set(list1) & set(list2))
print(result) #[9, 11, 20]
- It is O(n) time complexity
- Duplicate elements not allowed
- Order is not guarented.