'How to increment all values in a matrix (list of lists) by n?
I must create a function that is passed a matrix as an argument which then increments the value of each item in the matrix by n by using nested loops.
e.g if my matrix is [[8, 9], [4, 6], [7, 2]] and n = 1,
I want the output to be [[9, 10], [5, 7], [8, 3]]
Solution 1:[1]
You can create a function to return a new list using a nested list comprehension:
def increment_by_n(lst, n):
return [[col + n for col in row] for row in lst]
Usage:
>>> increment_by_n([[8, 9], [4, 6], [7, 2]], 1)
[[9, 10], [5, 7], [8, 3]]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Tomerikoo |
