Python 3: unpack inner lists in list comprehension

Posted by Beau Martínez on Stack Overflow See other posts from Stack Overflow or by Beau Martínez
Published on 2010-04-06T16:05:05Z Indexed on 2010/04/06 16:23 UTC
Read the original article Hit count: 512

I'm running the following code on a list of strings to return a list of its words:

words = [re.split('\\s+', line) for line in lines]

However, I end up getting something like:

[['import', 're', ''], ['', ''], ['def', 'word_count(filename):', ''], ...]

As opposed to the desired:

['import', 're', '', '', '', 'def', 'word_count(filename):', '', ...]

How can I unpack the lists re.split('\\s+', line) produces in the above list comprehension? Naïvely, I tried using * but that doesn't work.

(I'm looking for a simple and Pythonic way of doing; I was tempted to write a function but I'm sure the language accommodates for this issue.)

© Stack Overflow or respective owner

Related posts about python-3.x

Related posts about regex