-1

From a list, M:

M = [[1, 2, 3],
     [4, 5, 6],
     [7, 8, 9]]

I want to create a new list, L, with all items doubled.

So far, I have tried various combinations of iteration, comprehensions and lambda expressions, all to no avail.

What would be the easiest/fastest way?

Janus Syrak
  • 59
  • 1
  • 6
  • 4
    `[[x * 2 for x in r] for r in M]`? – awesoon Aug 22 '16 at 12:07
  • [Flatten the list of lists](https://stackoverflow.com/questions/952914), then perform your operation on each element of the flat list. – Kevin J. Chase Aug 22 '16 at 12:10
  • 1
    @KevinJ.Chase: The answers so far have assumed the new list `L` will have the same structure as `M` (not flattened). – Steven Rumbalski Aug 22 '16 at 12:39
  • @StevenRumbalski: Good point... I think we're all just assuming what the output should look like. Janus --- please [edit] your question to include the output list you want your example input to produce. – Kevin J. Chase Aug 22 '16 at 13:39
  • See also [How to map a function to a triple nested list and keep the triple nested list intact?](http://stackoverflow.com/questions/7273164/how-to-map-a-function-to-a-triple-nested-list-and-keep-the-triple-nested-list-in) – Steven Rumbalski Aug 22 '16 at 15:26

3 Answers3

4

A nested list comprehension will do:

double_M = [[2 * x for x in inner] for inner in M ]
>> [[2, 4, 6], [8, 10, 12], [14, 16, 18]]
DeepSpace
  • 78,697
  • 11
  • 109
  • 154
3

In case if you're using numpy, you could just double the entire matrix:

In [1]: import numpy as np

In [2]: M = [[1, 2, 3],
   ...:      [4, 5, 6],
   ...:      [7, 8, 9]]

In [3]: np.array(M) * 2
Out[3]: 
array([[ 2,  4,  6],
       [ 8, 10, 12],
       [14, 16, 18]])
awesoon
  • 32,469
  • 11
  • 74
  • 99
-1

Here's a little benchmark for fixed 3x3 matrices:

import numpy as np
import timeit

M = [[1, 2, 3],
     [4, 5, 6],
     [7, 8, 9]]


def f1(M):
    return [[x * 2 for x in r] for r in M]


def f2(M):
    return np.array(M) * 2

K=1000000
print(timeit.timeit('f1(M)', setup='from __main__ import f1, M', number=K))
print(timeit.timeit('f2(M)', setup='from __main__ import f2, M', number=K))

# 1.886869086403203
# 3.470187123186767
# [Finished in 5.6s]

I'd say f1 is a good choice in terms of speed

BPL
  • 9,632
  • 9
  • 59
  • 117
  • Probable reason is conversion to np.array in f2 while f1 returns default python list. If you add converstion (`np.array(***)`) in f1 result will be even slower than in f2 – Darth Kotik Aug 22 '16 at 12:50