As an alternative to list comprehensions, you could try map
:
>>> map(lambda x: [x], l)
[[1.0], [2.0], [3.0]]
This gives the desired result by applying the lambda
function (here, taking an object and putting it in a list) to each element of l
in turn.
In Python 3 map
returns an iterator so use list(map(lambda x: [x], l))
to get the list.
Using map
is about twice as slow as list comprehension for small lists of floats
because building the lambda
function incurs a small overhead:
>>> %timeit [[x] for x in l]
1000000 loops, best of 3: 594 ns per loop
>>> %timeit map(lambda x: [x], l)
1000000 loops, best of 3: 1.25 us per loop
For longer lists, the time gap between the two starts to close, although list comprehension remains the preferred option in the Python community.