Is it possible without loops initialize all list values to some bool? For example I want to have a list of N elements all False.
With * operator The * operator can repeat the same value required number of times. We use it to create a list with a Boolean value.
If you want to define a boolean in Python, you can simply assign a True or False value or even an expression that ultimately evaluates to one of these values. You can check the type of the variable by using the built-in type function in Python.
A boolean array can be created manually by using dtype=bool when creating the array. Values other than 0 , None , False or empty strings are considered True. Alternatively, numpy automatically creates a boolean array when comparisons are made between arrays and scalars or between arrays of the same shape.
A boolean list ("blist") is a list that has no holes and contains only true and false .
You can do it like this: -
>>> [False] * 10 [False, False, False, False, False, False, False, False, False, False]
NOTE: - Note that, you should never do this with a list
of mutable types
with same value, else you will see surprising behaviour like the one in below example: -
>>> my_list = [[10]] * 3 >>> my_list [[10], [10], [10]] >>> my_list[0][0] = 5 >>> my_list [[5], [5], [5]]
As you can see, changes you made in one inner list, is reflected in all of them.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With