C
C
CatRoys2020-06-19 21:51:03
Python
CatRoys, 2020-06-19 21:51:03

How to remove an element from a list if it is not in another list?

Can you tell me how to remove the elements of a list if it is not in another list?
Let's say we have two lists:

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

From list1, you need to remove all elements that are not in list2 and get the following list:
list1 = [2, 3, 5]

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2020-06-19
@CatRoys

list1 = [ n for n in list1 if n in list2 ]

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question