Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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]

like image 314
David Braun Avatar asked Oct 16 '25 14:10

David Braun


1 Answers

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

like image 105
Mortz Avatar answered Oct 18 '25 09:10

Mortz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!