python sample code:How to get duplicate values(intersection) from multiple lists

Published on:
Last updated:

This post is also available in: 日本語 (Japanese)

I'm writing a sample code about how to get duplicate values(intersection) from multiple lists
As a point, the return value of the set function is set type, so it is converted to list type with list function. And since the list is an unordered list, it is sorted with sorted function. If you keep it, I think the coding that follows will be smoother.

Sample code written for each step by step

# sample list
list_A = ["1","2","3","4","5"]
list_B = ["3","4","5","6","7"]
list_C = ["4","5","6","7","8"]

# Duplicate value extraction(intersection)
intersection_list = set(list_A) & set(list_B) & set(list_C)
print(type(intersection_list)) # <class 'set'> the return is set type
# convert to list
intersection_list = list(intersection_list)
# Since it is an unordered list, sort the list
intersection_list = sorted(intersection_list)
print(intersection_list) # ['4', '5']

Sample code written in simple line

# If you write the above code concisely, it becomes the following code.
list_A = ["1","2","3","4","5"]
list_B = ["3","4","5","6","7"]
list_C = ["4","5","6","7","8"]
# 
intersection_list = sorted(list(set(list_A) & set(list_B) & set(list_C)))
print(intersection_list) # ['4', '5']
No tags for this post.

About
Kuniyoshi Takemoto is the founder of Amelt.net LLC, and editor of this blog(www.amelt.net).Learn more and follow me on LinkedIn.