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.


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.

    my_list = [False for i in range(n)]

This will allow you to change individual elements since it builds each element independently.

Although, this technically is a loop.

When space matters, bytearray is a better choice. It's roughly five times more space efficient than the list of boolean solution.

This creates an array of N values, initialized to zero:

B = bytearray(N)

Need Your Help

Rails.cache error in Rails 3.1 - TypeError: can't dump hash with default proc

ruby-on-rails ruby ruby-on-rails-3 caching memcached

I running into an issue with the Rails.cache methods on 3.1.0.rc4 (ruby 1.9.2p180 (2011-02-18 revision 30909) [x86_64-darwin10]). The code works fine within the same application on 2.3.12 (ruby 1....

UITableViewCell Custom accessory - get the row of accessory

iphone uitableview ios4 row accessory

I have a pretty big issue. I am trying to create a favorite-button on every UITableViewCell in a UITableView. That works very good, and I currently have an action and selector performed when presse...