0

Where can I find documentation on the code below? Why does multiplying an array by 2, inserts another False into the array?

print( [False] * 2 )

output: [False, False]
2
  • That is not an array, it is a list Commented Mar 8, 2019 at 17:46
  • To answer your question as to where you can find the documentation that describes this behaviour please look at this and look at the 4th entry in the table in section 5.6 :) Commented Mar 8, 2019 at 17:52

3 Answers 3

4

It doubled the list. Basically multiplying the number of references inside the list. That is the expected behavior.

print(['a', 'b', 'c'] * 3)
['a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c']
Sign up to request clarification or add additional context in comments.

2 Comments

In other words, it basically concatenates itself X amount of times
0

For multiplying the numbers inside a list you need to iterate through it. The way you are multiplying gives the output that you are getting.

Comments

0

Python has a number of operator methods - the multiplication method is called __mul__ (https://docs.python.org/3.7/library/operator.html#operator.mul) Any class/module can define its own __mul__ method, which will be run when it is multiplied (which is what happens when you use *)

If you look at a list you can see it has __mul__ defined:

 ["a", "b"].__mul__
 <method-wrapper '__mul__' of list object at 0x7efc163fe9d0>

You can call this method with a number:

["a", "b"].__mul__(2)
["a", "b", "a", "b"]

1 Comment

Yep - typo - fixed it!

Your Answer

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.