Python iterates on the first elements of a list except the empty elements


This question already has an answer here:

  • Flattening a shallow list in Python [duplicate] 23 answers

I have scraped a website and retrieved the part where the author of a topic is stated. After extracting the authors, I have a list of lists of strings:

for post in topicsection:
    authorlist.append(re.findall(r'<a href="/[Mm]ember.*?">(.*?)</a>',

>>>> [['author1'],['author2'],['author3']]

However, I want to turn this into one list of strings. Therefore I looped over the authorlist and appended the first[0] element of every list to the Authorlist. Sometimes an empty lists appears in the text, which causes an error. I therefore want to use the try-except command, in which the empty lists are ignored.

How can I tell Python to extract the first element of every list, but continue the loop if there is an empty list? I tried the following, in which the except-part is not working:

    authorlist = [lijst[0] for lijst in authorlist]
except IndexError:

Thank you in advance!

You can have a conditional statement in your list comprehension

authorlist = [lijst[0] for lijst in authorlist if lijst]