-2

I don't understand how a boolean can by multiplied by a length. I'm fairly new to coding

def __init__(self, capacity, items):
        self.currentSolution = [False]*len(items) 
J French
  • 187
  • 7
  • 1
    have you tried it and printed it ? – azro May 04 '20 at 17:48
  • 2
    It's multiplying a list that contains one bool, it's not multiplying the bool. – jordanm May 04 '20 at 17:50
  • 2
    `[False]` isn't a Boolean, it's a list (whose only element happens to be Boolean). – Robin Zigmond May 04 '20 at 17:51
  • 1
    This is something you may use with care if the items are mutable. This is not the case but if you do something like `a=[[True, False, False]] * 5` and try to write `a[0][1] = False` you may end up with something unexpected... – FxIII May 04 '20 at 17:54

2 Answers2

3

The notation [value] * number builds a list containing value at each index, with a length of number

Example

[False]*2 => [False, False]
[False]*10 => [False, False, False, False, False, False, False, False, False, False]
azro
  • 53,056
  • 7
  • 34
  • 70
1

When you multiply a list by N it's actually creates a new list composed of N original lists.

Let me give you an example. When we'll use the following command:

[1, 2, 3] * 2

We'll get the following list:

[1, 2, 3, 1, 2, 3, 1, 2, 3]

So performing [False]*len(items) will actually create a list with the len of len(items) which every is False.

Another way to do the same thing could be:

[False for _ in range(len(items))]
desertnaut
  • 57,590
  • 26
  • 140
  • 166
MaBekitsur
  • 171
  • 8
  • `[False for _ in range(len(items))]` does the same thing just because False is immutable. The list comprehension evaluates the `False` statement multiple times while [False]*n returns n copies of `False` in a list. – FxIII May 04 '20 at 18:02
  • 1
    I'm not 100% sure, but I think that [False]*n creates a list with 1 False in it, then destroying it and creating new list of size N. [False for _ in range(len(items))], IMO, creates a lazy generator for N Falses and then creating one list out of it. Therefor I think that the way I suggested might be faster. Please correct me if I'm wrong :) – MaBekitsur May 05 '20 at 07:10