Search code examples
pythonlistmultidimensional-arraypaddingnested-lists

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.

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]