Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Python program to convert a list into a list of lists using a step value
When working with lists in Python, you may need to convert a flat list into a list of lists using a specific step value. This allows you to group elements and create nested structures from your data.
Method 1: Using List Slicing with Step Value
The most efficient approach uses list slicing to chunk the original list into smaller sublists ?
def convert_list_with_step(data, step):
result = []
for i in range(0, len(data), step):
result.append(data[i:i+step])
return result
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print("Original list:")
print(numbers)
print("\nConverted with step 3:")
print(convert_list_with_step(numbers, 3))
print("\nConverted with step 2:")
print(convert_list_with_step(numbers, 2))
Original list: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] Converted with step 3: [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]] Converted with step 2: [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]]
Method 2: Using List Comprehension
A more concise approach using list comprehension for the same result ?
def convert_with_comprehension(data, step):
return [data[i:i+step] for i in range(0, len(data), step)]
fruits = ['apple', 'banana', 'cherry', 'date', 'elderberry', 'fig']
print("Original list:")
print(fruits)
print("\nGrouped by 2:")
print(convert_with_comprehension(fruits, 2))
Original list: ['apple', 'banana', 'cherry', 'date', 'elderberry', 'fig'] Grouped by 2: [['apple', 'banana'], ['cherry', 'date'], ['elderberry', 'fig']]
Method 3: Converting Individual Strings to Lists
If you need to convert each string element into a separate list ?
def convert_strings_to_lists(data):
result = []
for element in data:
# Split by comma if present, otherwise wrap in list
if ',' in element:
sub_list = element.split(', ')
else:
sub_list = [element]
result.append(sub_list)
return result
names = ['peter', 'king', 'charlie', 'john, doe', 'alice, bob']
print("Original list:")
print(names)
print("\nConverted to list of lists:")
print(convert_strings_to_lists(names))
Original list: ['peter', 'king', 'charlie', 'john, doe', 'alice, bob'] Converted to list of lists: [['peter'], ['king'], ['charlie'], ['john', 'doe'], ['alice', 'bob']]
Comparison
| Method | Best For | Performance |
|---|---|---|
| List Slicing | Grouping by step size | Fast |
| List Comprehension | Concise grouping | Fastest |
| String Splitting | Processing comma-separated values | Moderate |
Conclusion
Use list slicing with step values to group elements efficiently. List comprehension provides the most concise syntax, while string splitting handles comma-separated data within list elements.
Advertisements
