Home > front end >  extending list of booleans by complements of another list of booleans
extending list of booleans by complements of another list of booleans

Time:06-21

Given two lists list1 and list2 of booleans , I want to extend list1 by the complements of the elements in list2. For example if

list1 = [True, True, False]
list2 = [False, False, True, False]

then after the operation

list1 = [True, True, False, True, True, False, True]  

while list2 shall remain unchanged.

What is the most pythonic way to achieve that?

CodePudding user response:

How about this:

list1.extend(not value for value in list2)

If there is a risk that list2 is an alias to list1, you are better off with

list1  = [not value for value in list2]

CodePudding user response:

temp_list = [not elem for elem in list2]
list1.extend(temp_list)

CodePudding user response:

If you want to generalize this to longer or more lists/arrays, you could have a look at numpy:

a1 = np.array([True, True, False])
a2 = np.array([False, False, True, False])
out = np.r_[a1, ~a2]

output: array([ True, True, False, True, True, False, True])

CodePudding user response:

Using the not keyword in the list comprehension, will just convert it to it's compliment.

list1.extend([not value for value in list2])

CodePudding user response:

The operator module provides the negation function, __not__.

from operator import __not__

list1.extend(map(__not__, list2))
print(list1)
  • Related