-2

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?

2 Answers2

1

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:]
Carl Sarkis
  • 119
  • 6
1
result = [fruits[-1], fruits[-2]]
print(result)
Freddie
  • 944
  • 9
  • 16