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
                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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With