56

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.

Rohit Jain
214k45 gold badges419 silver badges534 bronze badges
asked Nov 14, 2012 at 16:21

3 Answers 3

122

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.

answered Nov 14, 2012 at 16:22
Sign up to request clarification or add additional context in comments.

2 Comments

This is absolutely the correct idiom for this problem. However, it is absolutely the incorrect idiom to use when you're dealing with a mutable type: [[]]*10 has some surprising consequences for new comers :).
See this link why you shouldn't create a list of mutable types using multiplication.
19
 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.

Joel Christophel
2,6634 gold badges35 silver badges51 bronze badges
answered Nov 14, 2012 at 16:50

Comments

5

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)
answered Feb 24, 2017 at 18:34

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.