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)?
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.
Allows duplicate members. Use square brackets [] for lists. Tuple is a collection which is ordered and unchangeable. Allows duplicate members.
[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.
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).
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])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With