Common elements of Two list- Python Code

You are required to take two lists, say for example these two:

  a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
  b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]

and write a program that returns a list that contains only the elements that are common between the lists (without duplicates). Make sure your program works on two lists of different sizes.

Extras:

  1. Randomly generate two lists to test this
  2. Write this in one line of Python (don’t worry if you can’t figure this out at this point – we’ll get to it soon)

Here is the solution to this simple problem

#   program to find out common elements in these two list
#   program by      : rakesh kumar

a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] 
b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
common=[]
a = set(a)
b = set(b)
for x in a:
    if x in b:
        common.append(x)
print(common)

The output of the above program is like

as@DESKTOP-P84OH09 MINGW64 ~/desktop
$ c:/python37/python.exe c:/Users/as/Desktop/common_element.py
[1, 2, 3, 5, 8, 13]

if you have any other solution of the above problem, please send us via your comments.

 

 

Related Posts

If you like CBSEToaday and would like to contribute, you can also write an article using submit article or mail your article to contribute@cbsetoday.com See your article appearing on the cbsetoday.com main page and help other students/teachers.