Get the last element of a string of type in a list
4 answers
Once you have a given type, you can use several kinds of concepts to get what you need.
[el for el in lst if isinstance(el, given_type)][-1]
# Gives the last element if there is one, else IndexError
or
next((el for el in reversed(lst) if isinstance(el, given_type)), None)
# Gives the last element if there is one, else None
If this is something you do often enough, you can include it in a function:
def get_last_of_type(type_, iterable):
for el in reversed(iterable):
if isinstance(el, type_):
return el
return None
+12
source to share
Mandatory itertools
solution:
>>> l = [7, 'string 1', 'string 2', 8, 'string 3', 0, (1, 2, 3)]
>>> from itertools import dropwhile
>>> next(dropwhile(lambda x: not isinstance(x, str), reversed(l)), None)
'string 3'
If you cannot use imports for some reason, the polyfill for itertools.dropwhile
looks like this:
def dropwhile(predicate, iterable):
# dropwhile(lambda x: x<5, [1,4,6,4,1]) --> 6 4 1
iterable = iter(iterable)
for x in iterable:
if not predicate(x):
yield x
break
for x in iterable:
yield x
+2
source to share