Open In App

Python – Create nested list containing values as the count of list items

Last Updated : 06 Feb, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a list, the task is to write a Python program to create a nested list where the values are the count of list items.

Examples:

Input: [1, 2, 3]
Output: [[1], [2, 2], [3, 3, 3]]

Input: [4, 5]
Output: [[1, 1, 1, 1], [2, 2, 2, 2, 2]]

Method 1: Using nested list comprehension

The list will contain the count of the list items for each element e in the list we will create a list in the list with size e, in each list we will append the element e for e times.

Python3




l = [1, 2, 3, 4, 5]
l = [[i+1 for j in range(l[i])] for i in range(len(l))]
print(l)


Output:

[[1], [2, 2], [3, 3, 3], [4, 4, 4, 4], [5, 5, 5, 5, 5]]

Time Complexity :  O(N^2)

Space Complexity :  O(N^2)

Method 2:

The list will contain the count of the list items iterate the for loop for L times i.e. length of the list. Now at each element append a list, The appended list will be of the size count.

Python3




l = [1, 2, 3, 4, 5]
 
for i in range(len(l)):
    l[i] = [i+1 for j in range(i+1)]
     
print(l)


Output:

[[1], [2, 2], [3, 3, 3], [4, 4, 4, 4], [5, 5, 5, 5, 5]]

Time Complexity :  O(N^2)

Space Complexity :  O(N)

Method 3: Using *

Python3




l = [1, 2, 3, 4, 5]
nl=[]
for i in range(0,len(l)):
    j=[i+1]
    nl.append(j*l[i])
print(nl)


Output

[[1], [2, 2], [3, 3, 3], [4, 4, 4, 4], [5, 5, 5, 5, 5]]

Time Complexity :  O(N^2)

Space Complexity :  O(N)



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads