Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize list with same bool value

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.

like image 497
Alecs Avatar asked Nov 14 '12 16:11

Alecs


People also ask

How do you make a boolean list of values?

With * operator The * operator can repeat the same value required number of times. We use it to create a list with a Boolean value.

How do you initialize a boolean variable in Python?

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.

How do you initialize a boolean array 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.

Can a boolean be in a list?

A boolean list ("blist") is a list that has no holes and contains only true and false .


1 Answers

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.

like image 181
Rohit Jain Avatar answered Sep 19 '22 16:09

Rohit Jain