Get the last element of a string of type in a list

Let's say I have a list of different types:

i.e.

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

      

Is there a Pythonic way to return 'string 3'?

+3


source to share


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


I think the easiest way is to grab the last element of the filtered list.

filter(lambda t: type(t) is type(''), your_list)[-1]

      



or

[el for el in your_list if type(el) is type('')][-1]

      

+3


source


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


try it

lst = [7, 'string 1', 'string 2', [a, b c], 'string 3', 0, (1, 2, 3)]
filtered_string = [ x for x in lst if type(x) is str]

      

now you can get any of its index for the last index

filtered_string[-1]

      

0


source







All Articles