I noticed that you can multiply list by scalar but the behavior is weird If I multiply:
[2,3,4] * 3
I get:
[2,3,4,2,3,4,2,3,4]
I understand the results but what it's good for? Is there any other weird operations like that?
-
why down vote? i searched the site and didn't find an answer what does it good for?Liran Ben Haim– Liran Ben Haim2016年08月01日 09:44:08 +00:00Commented Aug 1, 2016 at 9:44
2 Answers 2
The main purpose of this operand is for initialisation. For example, if you want to initialize a list with 20 equal numbers you can do it using a for loop:
arr=[]
for i in range(20):
arr.append(3)
An alternative way will be using this operator:
arr = [3] * 20
More weird and normal list operation on lists you can find here http://www.discoversdk.com/knowledge-base/using-lists-in-python
Comments
The operation has a use of creating arrays initialized with some value.
For example [5]*1000 means "create an array of length 1000 initialized with 5".
If you want to multiply each element by 3, use
map(lambda x: 3*x, arr)