Python program to convert a list into a list of lists using a step value


When it is required to convert a list into a list of lists using a step value, a method is defined that uses a simple iteration, the ‘split’ method and the ‘append’ method.

Example

Below is a demonstration of the same

def convert_my_list(my_list):
   my_result = []
   for el in my_list:
      sub = el.split(', ')
      my_result.append(sub)

   return(my_result)

my_list = ['peter', 'king', 'charlie']
print("The list is :")
print(my_list)

print("The resultant list is :")
print(convert_my_list(my_list))

Output

The list is :
['peter', 'king', 'charlie']
The resultant list is :
[['peter'], ['king'], ['charlie']]

Explanation

  • A method named ‘convert_my_list’ is defined.

  • It takes a list as a parameter.

  • Inside it, an empty list is defined.

  • The list is iterated over, and split based on comma.

  • This list items are appended to the empty list.

  • Outside the method, a list is defined and is displayed on the console.

  • The method is called by passing this list.

  • The output is displayed on the console.

Updated on: 15-Sep-2021

112 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements