Update one list with respect to another list in python

Question:

I’m very new in python. I just stuck in one problem.
I have two lists, like –

list1 = [1,2,3,4,5]
list2 = [3,6,8,9,1,2,4,0,5]

Now I have to check each value of list1 with that it is present in list2 or not. If all the value of list1 is present in list2 then update the list2 by removing extra values from list2. So list2 will be like –

list2 = [3,1,2,4,5]

Tried to do this with nested loop. but it is reading only 1st value. how can I do that?

Asked By: Asmita Guha

||

Answers:

One of the many options for performing the task

list1 = [1, 2, 3, 4, 5]
list2 = [3, 6, 8, 9, 1, 2, 4, 0, 5]
list2 = [num for num in list2 if num in list1 and set(list1).issubset(list2)]
Answered By: nnekkitt
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.