Convert list into list of lists in Python

PythonServer Side ProgrammingProgramming

During data analysis we face scenarios to convert every element of a list into a sublist. So in this article we will need to take a normal list as an input and convert into a list of lists where each element becomes a sublist.

Using for loop

This is a very straight forward approach in which we create for loop to read each element. We read it as a list and store the result in the new list.

Example

 Live Demo

Alist = ['Mon','Tue','Wed','Thu','Fri']

#Given list
print("Given list: ",Alist)

# Each element as list
NewList= [[x] for x in Alist]

# Print
print("The new lists of lists: ",NewList)

Output

Running the above code gives us the following result −

Given list: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri']
The new lists of lists: [['Mon'], ['Tue'], ['Wed'], ['Thu'], ['Fri']]

With split

In this approach we use the split function to extract each of the elements as they are separated by comma. We then keep appending this element as a list into the new created list.

Example

 Live Demo

Alist = ['Mon','Tue','Wed','Thu','Fri']

#Given list
print("Given list: ",Alist)

NewList= []

# Using split
for x in Alist:
   x = x.split(',')
   NewList.append(x)

# Print
print("The new lists of lists: ",NewList)

Output

Running the above code gives us the following result −

Given list: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri']
The new lists of lists: [['Mon'], ['Tue'], ['Wed'], ['Thu'], ['Fri']]

Using map

The map function is used to apply the same function again and again to a sequence of parameters. So we use a lambda function to create a series of list elements by reading each element from the original list and apply map function to it.

Example

 Live Demo

Alist = ['Mon','Tue','Wed','Thu','Fri']

#Given list
print("Given list: ",Alist)

# Using map
NewList= list(map(lambda x:[x], Alist))

# Print
print("The new lists of lists: ",NewList)

Output

Running the above code gives us the following result −

Given list: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri']
The new lists of lists: [['Mon'], ['Tue'], ['Wed'], ['Thu'], ['Fri']]
raja
Published on 13-May-2020 14:50:25
Advertisements