How to insert string to each token of a list of strings?
<p>Lets assume I have the following list:</p>

<pre><code>l = ['the quick fox', 'the', 'the quick']
</code></pre>

<p>I would like to transform each element of the list into a url as follows:</p>

<pre><code>['&lt;a href="http://url.com/the"&gt;the&lt;/a&gt;', '&lt;a href="http://url.com/quick"&gt;quick&lt;/a&gt;','&lt;a href="http://url.com/fox"&gt;fox&lt;/a&gt;', '&lt;a href="http://url.com/the"&gt;the&lt;/a&gt;','&lt;a href="http://url.com/the"&gt;the&lt;/a&gt;', '&lt;a href="http://url.com/quick"&gt;quick&lt;/a&gt;']
</code></pre>

<p>So far, I tried the following:</p>

<pre><code>list_words = ['&lt;a href="http://url.com/{}"&gt;{}&lt;/a&gt;'.format(a, a) for a in x[0].split(' ')]
</code></pre>

<p>The problem is that the above list-comprehension just does the work for the first element of the list:</p>

<pre><code>['&lt;a href="http://url.com/the"&gt;the&lt;/a&gt;',
 '&lt;a href="http://url.com/quick"&gt;quick&lt;/a&gt;',
 '&lt;a href="http://url.com/fox"&gt;fox&lt;/a&gt;']
</code></pre>

<p>I also tried with a <code>map</code> but, it didn't work:</p>

<pre><code>[map('&lt;a href="http://url.com/{}"&gt;{}&lt;/a&gt;'.format(a,a),x) for a in x[0].split(', ')]
</code></pre>

<p>Any idea of how to create such links from the tokens of a list of sentences?</p>

<p>You were close, you limited your comprehension to the contents of <code>x[0].split</code>, i.e you were missing one <code>for</code> loop through the elements of <code>l</code>:</p>

<pre><code>list_words = ['&lt;a href="http://url.com/{}"&gt;{}&lt;/a&gt;'.format(a,a) for x in l for a in x.split()]
</code></pre>

<p>this works because <code>"string".split()</code> yields a one element list.</p>

<p>This can look <em>way prettier</em> if you define the format string outside the comprehension and use a positional index <code>{0}</code> informing <code>format</code> of the argument (so you don't need to do <code>format(a, a)</code>):</p>

<pre><code>fs = '&lt;a href="http://url.com/{0}"&gt;{0}&lt;/a&gt;'
list_words = [fs.format(a) for x in l for a in x.split()]
</code></pre>

<p>With <code>map</code> you can get an ugly little duckling too if you like:</p>

<pre><code>list(map(fs.format, sum(map(str.split, l),[])))
</code></pre>

<p>Here we <code>sum(it, [])</code> to flatten the list of lists <code>map</code> with <code>split</code> produces and then map <code>fs.format</code> to the corresponding flattened list. Results are the same:</p>

<pre><code>['&lt;a href="http://url.com/the"&gt;the&lt;/a&gt;',
 '&lt;a href="http://url.com/quick"&gt;quick&lt;/a&gt;',
 '&lt;a href="http://url.com/fox"&gt;fox&lt;/a&gt;',
 '&lt;a href="http://url.com/the"&gt;the&lt;/a&gt;',
 '&lt;a href="http://url.com/the"&gt;the&lt;/a&gt;',
 '&lt;a href="http://url.com/quick"&gt;quick&lt;/a&gt;']
</code></pre>

<p>Go with the comprehension, <em>obviously</em>.</p>

python string python-3.x list-comprehension