python - Get last element of type string in a list -


suppose have list of different types:

i.e.

[7, 'string 1', 'string 2', [a, b c], 'string 3', 0, (1, 2, 3)] 

is there pythonic way return 'string 3' ?

if have given type, can use several kinds of comprehensions need.

[el el in lst if isinstance(el, given_type)][-1] # gives last element if there one, else indexerror 

or

next((el el in reversed(lst) if isinstance(el, given_type)), none) # gives last element if there one, else none 

if you're doing enough, can factor function:

def get_last_of_type(type_, iterable):     el in reversed(iterable):         if isinstance(el, type_):             return el     return none 

Comments

Popular posts from this blog

php - failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request -

java - How to filter a backspace keyboard input -

java - Show Soft Keyboard when EditText Appears -