-1
Colors = ["yellow", "red", "green"]

I'm looking for new way to given the latest element of list. Is there a way without using of index [-1]?

user2390182
  • 72,016
  • 6
  • 67
  • 89

4 Answers4

2

You can call next on the reversed list:

next(reversed(Colors))
# 'green'
user2390182
  • 72,016
  • 6
  • 67
  • 89
2

Providing more context would help, as you could simply use Colors[len(Colors) - 1], but that still uses indexing. Another solution would be Colors.pop(), but keep in mind it will remove the last element.

gskhaled
  • 34
  • 4
1

In python, list class provides a function pop(), You can use Colors.pop()

Thekingis007
  • 627
  • 2
  • 16
0

How about this?

last = None
for x in Colors:
    last = x
print last
jochen
  • 3,728
  • 2
  • 39
  • 49
  • 1
    in this case the variable x isn't really necessary, you can do `for last in Colors: pass` for the same effect, but I guess is alright for extra clarity... – Copperfield Nov 17 '21 at 15:37