1

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?

Lafexlos
7,7555 gold badges42 silver badges55 bronze badges
asked Aug 1, 2016 at 9:38
1
  • why down vote? i searched the site and didn't find an answer what does it good for? Commented Aug 1, 2016 at 9:44

2 Answers 2

3

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

fodma1
3,5451 gold badge33 silver badges52 bronze badges
answered Aug 1, 2016 at 9:40
Sign up to request clarification or add additional context in comments.

Comments

1

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)
answered Aug 1, 2016 at 9:43

1 Comment

and its just for initialisation? why python writer did so weird operator instead of a simple init function?

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.