Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract first items from a list of tuples [duplicate]

I have a rather large list of tuples which contains:

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

I just want to extract the first string, so the output for the above list would be:

and
cx
is

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

like image 416
Custos Mortem Avatar asked Jul 29 '10 22:07

Custos Mortem


People also ask

How do you extract the first element of a tuple?

Use indexing to get the first element of each tuple Use a for-loop to iterate through a list of tuples. Within the for-loop, use the indexing tuple[0] to access the first element of each tuple, and append it.

Can list and tuple have duplicate values?

Allows duplicate members. Use square brackets [] for lists. Tuple is a collection which is ordered and unchangeable. Allows duplicate members.


3 Answers

[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.

like image 97
Matthew Flaschen Avatar answered Oct 17 '22 00:10

Matthew Flaschen


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).

like image 39
awesomo Avatar answered Oct 16 '22 23:10

awesomo


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])
like image 44
volting Avatar answered Oct 17 '22 00:10

volting