Skip to content

Instantly share code, notes, and snippets.

@DevJulianSalas
Last active February 9, 2018 04:18
Show Gist options
  • Save DevJulianSalas/d5bb0f372fdb808927470264118444d3 to your computer and use it in GitHub Desktop.
Save DevJulianSalas/d5bb0f372fdb808927470264118444d3 to your computer and use it in GitHub Desktop.
Keep the last fews elements from a list
#Give a list with N elements need to get 3 last elements from a list
# [1,4,2,4,1,2,3,5,6,3]
# The first solution that comes my head is iter about it and use append, pop or delete but
# there is a more elegant solution with a collection "datatypes" is an awesome feature.
import collections
numbers_list = [1,4,2,4,1,2,3,5,6,3]
last_three_numbers = collections.deque(numbers_list, 3)
#Result is deque([5, 3, 7], maxlen=3)
#Here deque method is a useful one to get items according to length for this case 3
#deque object has a lot features to work is a list-like with pop, reverse, extend apendleft and so on.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment