1

There are a few similar questions to this one but not exactly the same:

I want to dynamically decrease a given input array or list of lists. For example:

matrix = [[0,1,2], [3,4,5],[6,7,8]]

Starting at 0 I need to iterate through and remove the final index - the iterative. So the output I would like to store in a new list is:

#output
[0,1,2], ,[3,4], [6]] 
[0,1,2], ,[3,4], [6]] ==> which then flattens to [0,1,2,3,4,6]

Here's what I'm currently going after:

def get_list(matrix, stop_index):
    temp = [] 

    for i in range(0, stop_index):
        for m in matrix:
            temp.append(matrix[0:stop_index])
        outside_list.append(temp)

    return outside_list

I believe I am seeing well my over reliance on packages and libraries, so I am really trying to do this without outside packages or imports

Thank you for any help! I don't forget to green check mark.

phtaedrus
  • 27
  • 7

1 Answers1

1

Using list comprehension

l = [[0,1,2], [3,4,5],[6,7,8]]
ll = [ x[:len(l)-l.index(x)] for x in l]
# [[0, 1, 2], [3, 4], [6]]
print([x for y in ll for x in y ])
# [0, 1, 2, 3, 4, 6]

Simpler syntax:

    matrix = [[0,1,2], [3,4,5],[6,7,8]]
    outside_list = list()
    for i in range(len(matrix)):
        # matrix[i] is used to access very sublist in the matrix, 
        #[:3-i] is to slice every sublist from the beginning to (3 - current position)
        outside_list.append(matrix[i][:3-i])
    print(outside_list)

Some useful refernces

Marsilinou Zaky
  • 998
  • 4
  • 16