0

Make a list comprehension to return a list of numbers which are not present in another list of numbers.

Define a list of numbers alist from 1 to 50 using a list comprehension.

Define another list blist and store its values as

[2,3,5,7,11,13,17,19,23,29,31,37,41,43,47]

Make a list final using list comprehension which would contain elements which are in alist but not in blist.

Print final

alist = [x for x in range(1,51)]
blist = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47]
final = [i for i in range (len(alist)) if i not in blist ]
print (final)
sshashank124
  • 31,495
  • 9
  • 67
  • 76
  • I think i am missing something with comprehension applied to either of list – Manoj Gupta Jan 12 '20 at 11:08
  • What is your question here ? – JimShapedCoding Jan 12 '20 at 11:09
  • Objective is to obtain following - Make a list **final** using list comprehension which would contain elements which are in **alist** but not in **blist**. – Manoj Gupta Jan 12 '20 at 11:13
  • Could use set and decrease the bigger list from the smaller. Like in my answer: – JimShapedCoding Jan 12 '20 at 11:17
  • @sshashank124, Thanks for your quick response, but i am not sure as how only modifying **[i for i in range (len(alist)) if i not in blist ]** to **[i for i in alist if i not in blist ]** got the answer. I mean, **range** gets the complete list items right – Manoj Gupta Jan 12 '20 at 11:21
  • `range(len(...))` only gets the indices of the elements not the actual elements. Please accept the duplicate vote if your problem is resolved – sshashank124 Jan 12 '20 at 11:23

1 Answers1

0

You could use set() for this which would clean the duplicates in this case:

alist = [x for x in range(1,51)]
blist = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47]
final = set(alist) - set(blist)
print (list(final))

OUTPUT:

[1, 4, 6, 8, 9, 10, 12, 14, 15, 16, 18, 20, 21, 22, 24, 25, 26, 27, 28, 30, 32, 33, 34, 35, 36, 38, 39, 40, 42, 44, 45, 46, 48, 49, 50]
Community
  • 1
  • 1
JimShapedCoding
  • 849
  • 1
  • 6
  • 17