4

I am trying to get subsequence of items between 2 lists in a list of lists. For example, if I have

list=[[1,2,3,4],[],[6,9],[2],[3],[4]]

I want to extract the items ranging from list[0][1] until list[2][1] into another list. This resulting list would then be [2,3,4,6] (ignoring the empty list in between).

How can I do that? I have been trying to use a for i in range(...) loop but it is not working for me.

Zero Piraeus
  • 56,143
  • 27
  • 150
  • 160
A.Huq
  • 41
  • 2

2 Answers2

2

Assuming your list is called list_of_lists1, this list comprehension using enumerate() works:

[n for i, sub_list in enumerate(list_of_lists)
   for j, n in enumerate(sub_list)
   if (0, 1) <= (i, j) < (2, 1)]

1 It's a bad idea to call a list list as in your example, because that masks the name of the type list, which you then don't have access to.

Zero Piraeus
  • 56,143
  • 27
  • 150
  • 160
0

Try this:

def complex_slice(my_list, i, j, k):
    result = my_list[i][k:]
    for sub_list in my_list[ (i + 1) : (j - 1) ]:
        result.extend(sub_list)
    result.extend(my_list[j][:k])
    return result
Woody1193
  • 7,252
  • 5
  • 40
  • 90