If your list includes non-strings, e.g. mylist = [0, [1, 's'], 'string']
, then the answers on here would not necessarily work. In that case, using next()
to find the first string by checking for them via isinstance()
would do the trick.
next(e for e in mylist if isinstance(e, str))[:1]
Note that ''[:1]
returns ''
while ''[0]
spits IndexError
, so depending on the use case, either could be useful.
The above results in StopIteration
if there are no strings in mylist
. In that case, one possible implementation is to set the default value to None
and take the first character only if a string was found.
first = next((e for e in mylist if isinstance(e, str)), None)
first_char = first[0] if first else None