Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python get last 5 elements in list of lists

I have a list of lists like this: [[1, 2], [4, 5, 6], [], None, [7, 12, 14, 16]].

I want to write a function that will return: [16, 14, 12, 7, 6]: i.e. the last 5 elements in the list of lists.

This is the code I have, but it is not very pythonic at all (master_list contains the list above):

    def find_last_five():
        last_five = []
        limit = 5

        for sublist in reversed(master_list):
            # have to check that list is not None.
            if sublist:
                for elem in sublist:
                    last_five.append(elem)
                    limit -= 1
                    if (limit == 0):
                         return last_five

        return last_five
like image 685
Atul Bhatia Avatar asked Dec 08 '22 04:12

Atul Bhatia


1 Answers

import itertools as it

a = [[1, 2], [4, 5, 6], [], [7, 12, 14, 16]]
reversed(it.islice(it.chain.from_iterable(reversed(a)), 5))

That actually assumes there are no None's in a. If there are just do a = filter(a, None).

like image 138
U2EF1 Avatar answered Dec 31 '22 01:12

U2EF1