- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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.
Advertisements