dardub
dardub

Reputation: 3195

How do I get the last non-empty item in a list in Python?

I just started learning Python today.

I have a list:

[text:u'Oranges', text:u'Apples', empty:'', empty:'']

How do I get the last non-empty item in a list? In this case, 'Apples'.

I see in Get first non-empty string from a list in python, they get the first non-empty value. Not sure how to get the last.

Upvotes: 2

Views: 6073

Answers (2)

Gabriel Ross
Gabriel Ross

Reputation: 5198

This:

d = [1, 2, 3, "", 4, "", 5, ""]
last_non_empty = [i for i in d if i][-1]

Upvotes: 6

agf
agf

Reputation: 176910

next(s for s in reversed(list_of_string) if s)

If you really have a dictionary, use reversed(dictionary.values()), but keep in mind that anything you do to the dictionary can change it's ordering, and it's not ordered in a consistent way between different versions of Python even for a given state.

Use an OrderedDict if you want the keys kept in insertion order.

Upvotes: 9

Related Questions