Last active
February 9, 2018 04:18
-
-
Save DevJulianSalas/d5bb0f372fdb808927470264118444d3 to your computer and use it in GitHub Desktop.
Keep the last fews elements from a list
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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