I have a list :
fruits = ['apple', 'oranges', 'pineapples', 'mangoes', 'avocado', 'berries']
How do I extract the last and second last item on the list using python?
I have a list :
fruits = ['apple', 'oranges', 'pineapples', 'mangoes', 'avocado', 'berries']
How do I extract the last and second last item on the list using python?
Python offers a lot of ways to manage lists with custom indices, conditions...
fruits = ['apple', 'oranges', 'pineapples', 'mangoes', 'avocado', 'berries']
result = [fruits[-2], fruits[-1]] #Last and second last items
result2 = fruits[-2:-1] #All items between second last and the last items
result3 = fruits[-2:] #All items from the second last
All those variables will contain the same elements. In my point of view you should use the third one:
result = fruits[-2:]