Slobodan Stevic
Slobodan Stevic

Reputation: 348

How to multiply elements in the list in Python

I've found answers that tackle the question of how to multiply with the element value, but what concerns me is how to make copies of the element itself. I have:

a = [1, 2, 3]
x = 3
b = []

I tried:

b.append(a * x)

But that gives me:

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

and I need:

b = [[1, 2, 3], [1, 2, 3], [1, 2, 3]]

Please note I'm a programming novice. Thanks!

Upvotes: 1

Views: 646

Answers (1)

Ry-
Ry-

Reputation: 224905

If you need to copy the list and not a reference to the list, you can't use *.

b = [a[:] for i in range(x)]

(a[:] creates a copy of the list.)

Upvotes: 1

Related Questions