How to use re match objects in a list comprehension

[m.group(1) for l in lines for m in [regex.search(l)] if m]

The “trick” is the for m in [regex.search(l)] part — that’s how you “assign” a value that you need to use more than once, within a list comprehension — add just such a clause, where the object “iterates” over a single-item list containing the one value you want to “assign” to it. Some consider this stylistically dubious, but I find it practical sometimes.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)