Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Tuples - Retrieve unique elements in list of tuples

UPDATE:

I went with this:

set(item[1] for item in id) 

Thanks guys, your ideas helped me.


I am working with a list of tuples:

Using the following line of code as an example. My list can be of any lenght. However, I will always be looking for a given index of my tuples:

id = [(9,'Tup','Check'),(10,'Tup','Pyton'),(11,'Not Tup','Stack'),(12,'Not Tup','Stack')]

In this scenario, I am looking to grab the unique second elements.

objective_ouput = ('Tup','Not Tup')
like image 785
ruh Avatar asked Jun 26 '26 08:06

ruh


2 Answers

It as simple as follow:

objective_ouput_set = {item[1] for item in id}
like image 142
Dhia Avatar answered Jun 27 '26 22:06

Dhia


You can use a list comprehension.

tup = ()
tuple([t[1] for t in your_list_of_tuples if t[1] not in tup])

By the way, id is not a good variable name because it is a builtin.

like image 20
sam-pyt Avatar answered Jun 27 '26 23:06

sam-pyt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!