Multiply adjacency list by -1

g = [
    [4, 7],
    [3],
    [4, 5],
    [4],
    [2],
    [0]
]

I´m trying to multiply the adjacency list above using this piece of code:

for i in range(len(g)):
    for j in g[i]:
        g[i] = [j * (-1) for j in g[i]]
        

print(g)

the result i´m getting is:

[[4, 7], [-3], [4, 5], [-4], [-2], [0]]

what do i have to chage so all the list would be negative?

Upvotes: 1

Views: 66

Answers (1)

Andrej Kesely
Andrej Kesely

Reputation: 195508

To multiply every element in sublist by -1:

g = [[4, 7], [3], [4, 5], [4], [2], [0]]

g_neg = [[v * -1 for v in subl] for subl in g]
print(g_neg)

Prints:

[[-4, -7], [-3], [-4, -5], [-4], [-2], [0]]

Upvotes: 1

Related Questions