Best way to get the nth element of each tuple from a list of tuples in Python
<p>I had some code that contained <code>zip(*G)[0]</code> (and elsewhere, <code>zip(*G)[1]</code>, with a different G).  <code>G</code> is a list of tuples.  What this does is return a list of the first (or generally, for <code>zip(*G)[n]</code>, the <code>n-1</code>th) element of each tuple in G as a tuple.  For example, </p>

<pre><code>&gt;&gt;&gt; G = [(1, 2, 3), ('a', 'b', 'c'), ('you', 'and', 'me')]
&gt;&gt;&gt; zip(*G)[0]
(1, 'a', 'you')
&gt;&gt;&gt; zip(*G)[1]
(2, 'b', 'and')
</code></pre>

<p>This is pretty clever and all, but the problem is that it doesn't work in Python 3, because <code>zip</code> is an iterator there.  Furthermore, 2to3 isn't smart enough to fix it.  So the obvious solution is to use <code>list(zip(*G))[0]</code>, but that got me thinking: there is probably a more efficient way to do this.  There is no need to create all the tuples that zip creates.  I just need the <code>n</code>th element of each tuple in G.  </p>

<p>Is there are more efficient, but equally compact way to do this?  I'm OK with anything from the standard library.  In my use case, each tuple in G will be at least length <code>n</code>, so there is no need to worry about the case of zip stopping at the smallest length tuple (i.e., <code>zip(*G)[n]</code> will always be defined).</p>

<p>If not, I guess I'll just stick with wrapping the <code>zip</code> in <code>list()</code>.</p>

<p>(P.S., I know this is unnecessary optimization.  I'm just curious is all)</p>

<p><strong>UPDATE:</strong></p>

<p>In case anyone cares, I went with the <code>t0, t1, t2 = zip(*G)</code> option.  First, this lets me give meaningful names to the data. My <code>G</code> actually consists of length 2 tuples (representing numerators and denominators).  A list comprehension would only be marginally more readable than the zip, but this way is much better (and since in most cases the zip was list I was iterating through in a list comprehension, this makes things flatter).</p>

<p>Second, as noted by @thewolf and @Sven Marnach's excellent answers, this way is faster for smaller lists.  My G is actually not large in most cases (and if it is large, then this definitely won't be the bottleneck of the code!).</p>

<p>But there were more ways to do this than I expected, including the new <code>a, *b, c = G</code> feature of Python 3 I didn't even know about. </p>
