Home > Blockchain >  Print Latest element of list with out indexing
Print Latest element of list with out indexing

Time:11-18

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]?

CodePudding user response:

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.

CodePudding user response:

You can call next on the reversed list:

next(reversed(Colors))
# 'green'

CodePudding user response:

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

CodePudding user response:

How about this?

last = None
for x in Colors:
    last = x
print last

CodePudding user response:

i don't know why you want that but you can try [len(Colors)-1]

  • Related