python get last 5 elements in list of lists
list, list-comprehension, python
Solution
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)`.
Problem
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 ```