Python list of tuples, need to unpack and clean up

python, python-2.7

Solution

Easy solution, and the fastest in most cases.

[item[0] for item in x]
#or
[item for (item,) in x]

Alternatively if you need a functional interface to index access (but slightly slower):

from operator import itemgetter

zero_index = itemgetter(0)

print map(zero_index, x)

Finally, if your sequence is too small to fit in memory, you can do this iteratively. This is much slower on collections but uses only one item's worth of memory.

from itertools import chain

x = [('Edgar',), ('Robert',)]

# list is to materialize the entire sequence.
# Normally you would use this in a for loop with no `list()` call.
print list(chain.from_iterable(x))

But if all you are going to do is iterate anyway, you can also just use tuple unpacking:

for (item,) in x:
    myfunc(item)

Problem

Assume you have a list such as `x = [('Edgar',), ('Robert',)]` What would be the most efficient way to get to just the strings `'Edgar'` and `'Robert'`? Don't really want x[0][0], for example.

Original source