David Braun
David Braun

Reputation: 41

Multiplying a list in python --- deletes list

I was attempting to multiply a simple list in python by -1 and got an empty list back. Anyone know why?

I found how I want to do this using a lambda function, but I still need clarity.

L = list(range(10))
L = L * -1

The output was: []

I was expecting: [0, -1, -2, -3, -4, -5, -6, -7, -8, -9]

Upvotes: 4

Views: 73

Answers (1)

Mortz
Mortz

Reputation: 4879

What you are trying to achieve can be done by using list comprehensions -

L = [-1*x for x in L]

OR - shorten it to (as @wjandrea suggested in the comment below):

L = [-x for x in L]

When you multiply a list with an integer as you are attempting - you create a repeated list

L = [1]
L = L*3 #Returns [1, 1, 1]

If you multiply with a negative number or 0 - you will get an empty list

Upvotes: 2

Related Questions