views:

131

answers:

4

I have a rather large tuple which contains:

[('and', 44023), ('cx', 37711), ('is', 36777) .... ]

I just want to extract the first string delimited by the single quotes, so the output for the above tuple would be:

and
cx
is

How do I code this (with extensibilty built in to some degree)?

+10  A: 
[tup[0] for tup in mylist]

This uses a list comprehension. You could also use parentheses instead of the outer brackets to make it a generator comprehension, so evaluation would be lazy.

Matthew Flaschen
+1 for the note about generator comprehension. Didn't know it worked that way.
Mark
+1 for generator usage.
awesomo
-1 for generator usage. This breaks nearly half of the Zen of Python: python -c 'import this'
bukzor
@bukzor I believe adding the outer parentheses would **explicitly** make it a generator (no one did it behind your back).
awesomo
What does using a generator instead of a list comprehension have anything to do with being explicit or implicit?
orangeoctopus
@orangeoctopus My comment was in reference to bukzor's comment before it was edited. I think the above solution is clear and pythonic.
awesomo
@awesomeo My comment was in reference to his, too :)
orangeoctopus
A: 

You can unpack your tuples in a for loop, like so:

for word, count in mytuple:
    print "%r is used %i times!" % (word, count)

You can see this used extensively in the Python docs: http://docs.python.org/tutorial/datastructures.html#looping-technique

bukzor
+2  A: 

Just to provide an alternative way to the solution by Matthew.

tuples = [('and', 44023), ('cx', 37711), ('is', 36777) .... ]
strings, numbers = zip(*tuples)

In case you at some point decide you want both parts of the tuple in separate sequences (avoids two list comprehensions).

awesomo
if your list is really quite large, note that this doubles your memory requirements.
bukzor
A: 

If you want to get the exact output

and
cx
is

Then use a list comprehension in combination with the strings join method to join the newline chararcter like so

yourList = [('and', 44023), ('cx', 37711), ('is', 36777)]
print '\n'.join([tup[0] for tup in yourList])
volting