I have a tuple of tuples and I want to put the first value in each of the tuples into a set. I thought using map() would be a good way of doing this the only thing is I can't find an easy way to access the first element in the tuple. So for example I have the tuple ((1,), (3,))
. I'd like to do something like set(map([0], ((1,), (3,))))
(where [0]
is accessing the zeroth element) to get a set with 1 and 3 in it. The only way I can figure to do it is to define a function: def first(t): return t[0]
. Is there anyway of doing this in one line without having to declare the function?
We can iterate through the entire list of tuples and get first by using the index, index-0 will give the first element in each tuple in a list. Example: Here we will get the first IE student id from the list of tuples.
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.
In the majority of programming languages when you need to access a nested data type (such as arrays, lists, or tuples), you append the brackets to get to the innermost item. The first bracket gives you the location of the tuple in your list. The second bracket gives you the location of the item in the tuple.
Use a list comprehension:
data = ((1,), (3,))
print([x[0] for x in data])
Use operator.itemgetter
:
from operator import itemgetter
map(itemgetter(0), ((1,), (3,)))
While the list comprehensions are generally more readable, itemgetter
is closest to what you asked for. It's also a bit faster:
>>> from timeit import timeit
>>> setup = 'from operator import itemgetter; lst=( ("a",), ("b",), (1,), (2,))'
>>> timeit('map(itemgetter(0), lst)', setup=setup)
0.13061050399846863
>>> timeit('[i[0] for i in lst]', setup=setup)
0.20302422800159547
my_set = {x[0] for x in TUPLES}
Just another way to get it:
set(x for x, in data)
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