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
Python - Create nested list containing values as the count of list items
When it is required to create a nested list containing values as the count of list elements, a simple iteration and list comprehension can be used. This technique replaces each element with a list containing repeated values based on the element's position.
Example
Below is a demonstration of creating nested lists where each position contains a list with repeated values ?
my_list = [11, 25, 36, 24]
print("The original list is:")
print(my_list)
for element in range(len(my_list)):
my_list[element] = [element + 1 for j in range(element + 1)]
print("The resultant nested list is:")
print(my_list)
The output of the above code is ?
The original list is: [11, 25, 36, 24] The resultant nested list is: [[1], [2, 2], [3, 3, 3], [4, 4, 4, 4]]
How It Works
The algorithm works by iterating through each position in the list:
Position 0: Creates [1] − one element with value 1
Position 1: Creates [2, 2] − two elements with value 2
Position 2: Creates [3, 3, 3] − three elements with value 3
Position 3: Creates [4, 4, 4, 4] − four elements with value 4
Alternative Approach Using Enumerate
You can also use enumerate() for a more Pythonic approach ?
my_list = [11, 25, 36, 24]
print("The original list is:")
print(my_list)
result_list = []
for index, value in enumerate(my_list):
nested_item = [index + 1] * (index + 1)
result_list.append(nested_item)
print("The resultant nested list is:")
print(result_list)
The original list is: [11, 25, 36, 24] The resultant nested list is: [[1], [2, 2], [3, 3, 3], [4, 4, 4, 4]]
One-Line Solution
For a more concise solution, you can use list comprehension ?
my_list = [11, 25, 36, 24]
result = [[i + 1] * (i + 1) for i in range(len(my_list))]
print("Original:", my_list)
print("Result:", result)
Original: [11, 25, 36, 24] Result: [[1], [2, 2], [3, 3, 3], [4, 4, 4, 4]]
Conclusion
Use list comprehension with range(len()) to create nested lists based on position indices. The pattern creates sublists where each position contains repeated values equal to the position number plus one.
