0

How to increase plus 2 all elements of lists ?

My code is: m=[[1,2,3], [4,5,6],[7,8,9]] print([r[0] + 2 for r in m] but it will increase only 1 element from every list

7th Oct 2020, 7:27 PM
Martyna Tomaszewska
Martyna Tomaszewska - avatar
6 Answers
+ 6
this can be done with 2 nested loops and an enumerator for the index: nums = [[1,2,3], [4,5,6],[7,8,9]] for lst in nums: for index, num in enumerate(lst): lst[index] = num +2 print(nums) # result is: [[3, 4, 5], [6, 7, 8], [9, 10, 11]]
7th Oct 2020, 7:47 PM
Lothar
Lothar - avatar
+ 5
m = [[1,2,3], [4,5,6], [7,8,9]] m = [[*map(lambda el: el+2, el)] for el in m] print(m)
7th Oct 2020, 8:52 PM
Vitaly Sokol
Vitaly Sokol - avatar
+ 3
Lothar , thanks. Fixed.
7th Oct 2020, 8:00 PM
Shadoff
Shadoff - avatar
+ 2
m=[[1,2,3],[4,5,6],[7,8,9]] n=[] for i in m: k=[] for j in i: k+=[j+2] n+=[k] print(n)
7th Oct 2020, 7:38 PM
Shadoff
Shadoff - avatar
+ 2
Thank You all :)
12th Oct 2020, 7:41 PM
Martyna Tomaszewska
Martyna Tomaszewska - avatar
+ 1
Check the performance of different ways of doing it as suggested by people here, The first one is the code I came up with(similar to one by Vitaly) which is a little expensive https://code.sololearn.com/c8JJsWQOs0FO/?ref=app Lastly the best implementation will depend based on large input size but still I just wanted to see how they perform
7th Oct 2020, 9:50 PM
Abhay
Abhay - avatar