tmsblgh
tmsblgh

Reputation: 527

How to make a list with elements to list with list with only one element?

I have a list with n elements but i would like to convert it to a list which contains n list, and every list contains a single element.

 a = ['1','2','3','4']
 b = [['1'],['2'],['3'],['4']]

How can I make from a to b?

Upvotes: 3

Views: 753

Answers (4)

Harshit Anand
Harshit Anand

Reputation: 702

Very Simple Solution Could be from generators

 a = ['1','2','3','4']
 b = [[item] for item in a]

Upvotes: 0

Julien Spronck
Julien Spronck

Reputation: 15433

You can use map:

b = list(map(lambda x: [x], a))

or a list comprehension:

b = [[i] for i in a]

Upvotes: 3

prompteus
prompteus

Reputation: 1032

You can iterate through the a list and append new list with the item to b list.

a = ['1','2','3','4']
b = []
for i in range(len(a)):
    b.append([a[i]])

print(b)

This is basically the same solution as the one from JRodDynamite, but more readable for beginners.

Upvotes: 0

JRodDynamite
JRodDynamite

Reputation: 12613

You can try list comprehension

b = [[i] for i in a]

Upvotes: 5

Related Questions