Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I pad a nested list in python?

I have a very long nested list with the following irregular structure:

[[[1,2,3], [1,2,3], [1,2,3]],
 [[1,2,3], [1,2,3]],
 [[1,2,3], [1,2,3], [1,2,3], [1,2,3]],
  ...]

I would like to pad it with -10 at the beginning to look like below:

[[[-10,-10,-10], [-10,-10,-10], [1,2,3], [1,2,3], [1,2,3]],
 [[-10,-10,-10], [-10,-10,-10], [-10, -10, -10], [1,2,3], [1,2,3]],
 [[-10,-10,-10], [1,2,3], [1,2,3], [1,2,3], [1,2,3]],
  ...]

Where the second level of the nested list has 5 elements, each with 3 numbers.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I cannot use np.pad, because I cannot convert the irregular length list to an array.

Thank you in advance as I am a beginner.

>Solution :

You have a list of lists of 3-element lists.
You want to make it a list of 5-element lists of 3-element lists.
If there are not enough elements in a second-level list, you want to add [-10, -10, -10] at the beginning of the list.

new_list = []
for second_level in old_list:
    new_second_level = [[-10, -10, -10]] * (5-len(second_level)) + second_level 
    new_list.append(new_second_level)

I assumed that there is no 6-or-more-element list in the second level.
Note that you can replicate a list multiple times using the * operator.
As examples,

>>> [1, 2, 3] * 3
[1, 2, 3, 1, 2, 3, 1, 2, 3]
>>> [[1, 2, 3]] * 3
[[1, 2, 3], [1, 2, 3], [1, 2, 3]]

In a short version using a list comprehension,

new_list = [[[-10, -10, -10]] * (5 - len(second_level)) + second_level for second_level in old_list]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading