Home > OS >  Update one list with respect to another list in python
Update one list with respect to another list in python

Time:10-25

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?

CodePudding user response:

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)]
  • Related