-3

I want to make a list negative among the lists of list

I tried this

X=[[1,2,3],[4,5,6]]
X[0]=-X[0]

But it produces error I want the output as

X=[[-1,-2,-3],[4,5,6]]
depperm
  • 10,606
  • 4
  • 43
  • 67

2 Answers2

0

You have to iterate through the elements and multiply them with -1.

  • You cant use -X[0] because that is not proper python syntax for a list object

  • You can't use X[0]*-1 because that is a list and * operator doesn't do elementwise multiplication for a list object.

X=[[1,2,3],[4,5,6]]

X[0] = [-1*i for i in X[0]]
X
[[-1, -2, -3], [4, 5, 6]]
Akshay Sehgal
  • 18,741
  • 3
  • 21
  • 51
0

Use list comprehension:

X[0] = [-n for n in X[0]]

Or numpy if you want to multiply arrays by a number:

import numpy as np
X = np.array([[1,2,3],[4,5,6]])
X[0] = -X[0]
Jonathan Dauwe
  • 317
  • 2
  • 6