0

If I have a list as follows:

lst = [[0,1,2,3,4,5], [6,7,8,9,10,11], [18,19,20,21,22,23], [24,25,26,27,28,29]]

I would like to multiply each value by a factor of 2 so the output is:

lst = [[0,2,4,6,8,10], [12,14,16,18,20,22], [36,38,40,42,44,46], [48,50,52,54,56,58]]

I preferably want to do this in a function by processing the data row by row and column by column.

Michael M.
  • 10,486
  • 9
  • 18
  • 34
holvic
  • 27
  • 1

3 Answers3

1

Here are several ways to reach the result based on conciseness:

lst = [[0,1,2,3,4,5], [6,7,8,9,10,11], [18,19,20,21,22,23], [24,25,26,27,28,29]]

# beginner level - using nested for loops
lst_mul_by_2 = []

for i in range(len(lst)):
   temp = []
   for j in range(len(lst[i])):
       temp += [lst[i][j] * 2]
   lst_mul_by_2.append(temp)

# intermediate level - using list comprehensions
lst_mul_by_2 = [[i * 2 for i in sub_list] for sub_list in lst]

# advanced level - using lambda expressions 
lst_mul_by_2 = [*map(lambda x: [*map(lambda y: y * 2, x)], lst)]
Isaias
  • 11
  • 1
  • 2
  • 1
    Using `map` isn't better or more advanced than list comprehension. If anything it just makes the code messier. – Michael M. May 01 '23 at 13:33
  • In fact, it is likely slower. See [this answer](https://stackoverflow.com/a/1247490/13376511). – Michael M. May 01 '23 at 13:34
  • I assigned the difficulty levels based on the complexity and conciseness to write not on performance. – Isaias May 01 '23 at 14:34
0

You can try using below code -

new_lst = [[2 * i for i in _lst] for _lst in lst]
Pravash Panigrahi
  • 701
  • 2
  • 7
  • 21
0

A solution using numpy.multiply:

import numpy as np

lst = np.array([
  [0, 1, 2, 3, 4, 5],
  [6, 7, 8, 9, 10, 11],
  [18, 19, 20, 21, 22, 23],
  [24, 25, 26, 27, 28, 29]
])

print(np.multiply(lst, 2))

'''
[[ 0  2  4  6  8 10]
 [12 14 16 18 20 22]
 [36 38 40 42 44 46]
 [48 50 52 54 56 58]]
'''
InSync
  • 4,851
  • 4
  • 8
  • 30