Extracting a set from a list of composite elements in python
<p>I'm maintaining <code>message_id</code> and <code>message_writer_id</code> together in a python list like so:</p>

<pre><code>composite_items = ['1:2', '2:2', '3:2', '4:1', '5:19', '20:2', '45:1', ...]
</code></pre>

<p>Where each element is <code>message_id:message_poster_id</code>. </p>

<p>From the above list, I want to extract the <code>set</code> of all <code>message_writer_ids</code>. I.e. I want to extract a <code>set</code> containing all unique numbers <em>after</em> <code>:</code> so that I end up with: </p>

<pre><code>item_set = ['2', '1', '19']
</code></pre>

<p>What's the most efficient way to do that in python?</p>

<hr>

<p>Currently, I'm thinking I'll do something like:</p>

<pre><code>new_list = []
for item in composite_items:
    element = item.split(":")[1]
    new_list.append(element)
new_set = set(new_list)
</code></pre>

<p>Was wondering if there's  a faster way to achieve this. </p>

<p>You may use set comprehension like so:</p>

<pre><code>new_set = {item.partition(":")[2] for item in composite_items}
</code></pre>

<p>Set comprehension is fast, and unlike <code>str.split()</code>, <code>str.partition()</code> splits only once and stops looking for more colons. Quite the same as with <code>str.split(maxsplit=1)</code>.</p>

python