Reputation: 196
How can I turn a list like:
a = [1, 2, 3, 4, 5]
to something like:
b = [[1], [2], [3], [4], [5]]
I was thinking of using the map
function, but then what function would I exactly map a to?
Upvotes: 2
Views: 1038
Reputation: 5888
List comprehension are great for this kinda of thing. I simply put each individual item in a list inside the comprehension. Using map for this would be harder to accomplish.
a = [1, 2, 3, 4, 5]
b = [[i] for i in a]
Edit: List comprehensions are a shorthand for writing small pieces of code inside a loop. The "loop over something and create a new list" paradigm is so common that python decided to create specific syntax to handle this usage. Note that there's also dictionary and set comprehensions for similar usage.
Upvotes: 0
Reputation: 7490
What you ask can be done in a single line with a list comprehension:
a = [1, 2, 3, 4, 5]
b = [[x] for x in a]
print(b)
Output:
[[1], [2], [3], [4], [5]]
Upvotes: 0
Reputation: 71522
Using a comprehension is the easiest way IMO:
>>> [[x] for x in [1, 2, 3, 4, 5]]
[[1], [2], [3], [4], [5]]
You could also use map
and a lambda
:
>>> list(map(lambda x: [x], [1, 2, 3, 4, 5]))
[[1], [2], [3], [4], [5]]
Upvotes: 2