Ahmed Anwer
Ahmed Anwer

Reputation: 196

How to wrap each item of a list into its proper list

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

Answers (4)

Exelian
Exelian

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

Roberto Caboni
Roberto Caboni

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

Samwise
Samwise

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

me_
me_

Reputation: 743

use zip(a):

zip returns a list of iterables

Upvotes: 0

Related Questions