Given two lists containing numbers as input to the Python program,
the Python program should identify the common items present between two
lists and then print it.
I will be using a simple list comprehension method to find the common items present in two lists.
Write A Python Program To Find Common Items From Two Lists
Let's
take a variable named length and using The input function call ask the
user to enter the list1 length. take a empty list and iterate after
list one length and using the input function call accept the list one
elements from the user and then append it to the list1
length = int(input("Enter List1 Length : "))
list1 = []
for _ in range(length):
temp = int(input("Enter List1 Item : "))
list1.append(temp)
Take
the length variable again and ask user to enter the second list length,
Take empty list variable and iterate up to second list length and using
the input function call ask user to enter the second list items. once
the user enters the second list items up and it to the second list
using append() function call.
length = int(input("Enter List2 Length : "))
list2 = []
for _ in range(length):
temp = int(input("Enter List2 Item : "))
list2.append(temp)
Using
the list comprehension method, iterate the list1 items and check if
the item is present in the list2 if so set the item as common.
common_items = [item for item in list1 if item in list2]
the
list comprehension method will give as the common elements present in
both the list, once we get the common list item using the print
function call print all the items that are common between two lists
print("The common items from two lists are ...")
for item in common_items:
print(item, end=" ")
Python Program
====================
length = int(input("Enter List1 Length : "))
list1 = []
for _ in range(length):
temp = int(input("Enter List1 Item : "))
list1.append(temp)
length = int(input("Enter List2 Length : "))
list2 = []
for _ in range(length):
temp = int(input("Enter List2 Item : "))
list2.append(temp)
common_items = [item for item in list1 if item in list2]
print("The common items from two lists are ...")
for item in common_items:
print(item, end=" ")
Output
===============
Enter List1 Length : 3
Enter List1 Item : 1
Enter List1 Item : 2
Enter List1 Item : 3
Enter List2 Length : 5
Enter List2 Item : 12
Enter List2 Item : 1
Enter List2 Item : 24
Enter List2 Item : 3
Enter List2 Item : 5
The common items from two lists are ...
1 3
Conclusion
===================
execute
the above Python program by providing two lists containing numbers as
an input and note down the common items present between two lists.
comment it down below if you have any suggestions to improve the above Python program
0 Comments