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 is used.

Example

Below is a demonstration of the same

my_list = [11, 25, 36, 24]
print("The 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 list is :")
print(my_list)

Output

The list is :
[11, 25, 36, 24]
The resultant list is :
[[1], [2, 2], [3, 3, 3], [4, 4, 4, 4]]

Explanation

  • A list is defined and is displayed on the console.

  • It is iterated over, and it is added to 1 and converted to a list.

  • This is converted to a list.

  • This is the output that is displayed on the console.

Updated on: 21-Sep-2021

167 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements