Python – limit output from a sort method


if my views code is:

arttags = sorted(arttags, key=operator.attrgetter('date_added'), reverse=True)

what is the argument that will limit the result to 50 tags?

I'm assuming this:

.... limit=50)

is incorrect.

more complete code follows:

videoarttags = Media.objects.order_by('date_added'),filter(topic__exact='art') 
audioarttags = Audio.objects.order_by('date_added'),filter(topic__exact='art') 
conarttags = Concert.objects.order_by('date_added'),filter(topic__exact='art') 
arttags = list(chain(videoarttags, audioarttags, conarttags)) 
arttags = sorted(arttags, key=operator.attrgetter('date_added'), reverse=True) 

how do incorporate –


Best Solution

what about heapq.nlargest:
Return a list with the n largest elements from the dataset defined by iterable.key, if provided, specifies a function of one argument that is used to extract a comparison key from each element in the iterable: key=str.lower Equivalent to: sorted(iterable, key=key, reverse=True)[:n]

>>> from heapq import nlargest
>>> data = [1, 3, 5, 7, 9, 2, 4, 6, 8, 0]
>>> nlargest(3, data)
[9, 8, 7]