How to get last items of a list in Python?
To fetch the last N elements in a list, slice it using [-N:]
.
The slice gets the N
th item from the end up to the last item.
Slice and dice like a Python pro
- Negative indexing
- To put it simply, Python has a 'go back home' shortcut - a negative index.
-
Not just reversing a list, it's like walking home backwards. You reach home but with a twist!
-
Slice objects
- They are like placeholders but with swords - slicing wherever they go.
Utilize external libraries and itertools
Non-list iterables can be pretty elusive guys. They won't let you use negative indexing. So, enter itertools.islice
, it's almost like a ninja slicer.
islice
fetches elements in a lazy manner, useful when you're dealing with big data sets or streaming data.
The more_itertools
library is another knight in the shining armor. Use it for an enhanced slicing experience:
It's like saying, "Hey iterable! Show me your tail."
Best practices
Beware of the Edge (Cases)
Even with Python's forgiving nature, there are edge cases. If the slicing goes overboard, Python won't complain but it may not give you what you expected:
Python being like: "That's all I have, take it."
Keep an eye on performance
Slicing creates a new list. If the original list is Godzilla-sized, you might end up with two monstrous lists in your memory.
In the world of Python, Memory is money!
Was this article helpful?