'How to toggle between booleans (in a list or tuple)?

i = True
j = False
t = (i,j)
for i in t:
    if i:
        i = not i
        
print (t)
(True, False)

For example, I want to change all values in a tuple to False, no matter the element was True or False before. How can I realise that?



Solution 1:[1]

You can do this with a list comprehension:

t = [False for _ in t]

or

t = tuple(False for _ in t)

if you want a tuple.

Your method doesn’t work because (imprecisely) i = not i does not change the value of i, it makes a new i, with a different value, so the ‘original’ value in your tuple is unaffected.

Solution 2:[2]

You need to create a new Tuple.

In fact it seems you need a Tuple with only False in it:

i = True
j = False
t = (i,j)
t = Tuple([False] * len(t))

Solution 3:[3]

i = True
j = False
t = (i,j)
result = ()
for i in range(len(t)):
    result = result + (False,)

print(result)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 LeopardShark
Solution 2 quamrana
Solution 3 Shreyas Singh