Python program to mask a list using values from another list

PythonServer Side ProgrammingProgramming

When it is required to mask a list with the help of values from another list, list comprehension is used.

Example

Below is a demonstration of the same

my_list = [5, 6, 1, 9, 11, 0, 4]

print("The list is :")
print(my_list)

search_list = [2, 10, 6, 3, 9]

result = [1 if element in search_list else 0 for element in my_list]

print("The result is :")
print(result)

Output

The list is :
[5, 6, 1, 9, 11, 0, 4]
The result is :
[0, 1, 0, 1, 0, 0, 0]

Explanation

  • A list is defined and is displayed on the console.

  • Another list of elements is defined.

  • The list comprehension is used to iterate through the list and search for the element in the list.

  • The results are assigned to a variable.

  • This result is displayed on the console.

raja
Published on 21-Sep-2021 07:04:15
Advertisements