user7891984
user7891984

Reputation: 99

Slicing nested list by index in python

I have a nested list with unequal length: [[1,2,3],[4,5],[6,7,8]] and I have a start_index=(i,j) and end_index=(a,b) and I need to print all elements between start_index and end_index. For example if start_index=(1,1) and end_index=(2,2) then I will print (5,6,7,8)

Upvotes: 2

Views: 265

Answers (1)

rassar
rassar

Reputation: 5680

You can use the following function:

def nested_index(arr, start, end):
    res = arr[start[0]][start[1]:]
    for i in range(start[0] + 1, end[0]):
        res.extend(arr[i])
    res.extend(arr[end[0]][:end[1] + 1])
    return res

>>> print(nested_index([[1,2,3],[4,5],[6,7,8]], (1, 1), (2, 2)))
[5, 6, 7, 8]

Upvotes: 3

Related Questions