If I have, for example, a list of tuples such as
a = [(1,2)] * 4
how would I create a list of the first element of each tuple? That is, [1, 1, 1, 1].
Use a list comprehension:
>>> a = [(1,2)] * 4
>>> [t[0] for t in a]
[1, 1, 1, 1]
You can also unpack the tuple:
>>> [first for first,second in a]
[1, 1, 1, 1]
If you want to get fancy, combine map and operator.itemgetter. In python 3, you'll have to wrap the construct in list to get a list instead of an iterable:
>>> import operator
>>> map(operator.itemgetter(0), a)
<map object at 0x7f3971029290>
>>> list(map(operator.itemgetter(0), a))
[1, 1, 1, 1]
There are several ways:
>>> a = [(1,2)] * 4
>>> # List comprehension
>>> [x for x, y in a]
[1, 1, 1, 1]
>>> # Map and lambda
>>> map(lambda t: t[0], a)
[1, 1, 1, 1]
>>> # Map and itemgetter
>>> import operator
>>> map(operator.itemgetter(0), a)
[1, 1, 1, 1]
The technique of using map fell out of favor when list comprehensions were introduced, but now it is making a comeback due to parallel map/reduce and multiprocessing techniques:
>>> # Multi-threading approach
>>> from multiprocessing.pool import ThreadPool as Pool
>>> Pool(2).map(operator.itemgetter(0), a)
[1, 1, 1, 1]
>>> # Multiple processes approach
>>> from multiprocessing import Pool
>>> def first(t):
return t[0]
>>> Pool(2).map(first, a)
[1, 1, 1, 1]
[(1,2)] * 4.operator.itemgetter(0) is minimal. A multithreaded approach is only useful if the operation you're applying on each element is slow.a = [(1,2)] * 4
first_els = [x[0] for x in a]
tuple as a variable name. In particular don't use it as the name of a list!Assuming you have a list of tuples:
lta = [(1,2), (2,3), (44,45), (37,38)]
access the first element of each tuple would involve subscripting with [0], and visiting each tuple to extract each first element would involve a a list comprehension, which can be assigned to a variable as shown below:
resultant_list = [element[0] for element in lta]
>>> resultant_list
[1, 2, 44, 37]
I recently found out about Python's zip() function. Another way to do what I want to do here is:
list( zip( *a )[0] )
tup_list = zip( list1, list2 ) interleaves two lists into a list of 2-tuples, but zip( *tup_list ) does the opposite, resulting in a list of a tuple of list1 and a tuple of list2.