Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is there a way to get the same first or second element tuple in a list?

I’ve struggled with this question for a long time, and I didn’t find much useful information online. I tried to use for loop, but I can use it like c++ with an index like i+2 to get that element. If I have a list like [(0, 2), (1, 2), (2, 2), (2, 3), (3, 5), (4, 5), (4, 6), (4, 7)]. There are several tuples on the list. 4 appear three times as the first element of tuples. And 2 appear three times as the second element of tuples. How can I get (4, 5), (4, 6), (4, 7) and [(0, 2), (1, 2), (2, 2)out from the list because they have the same element of the tuple?

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You can use filter here

lst = [(0, 2), (1, 2), (2, 2), (2, 3), (3, 5), (4, 5), (4, 6), (4, 7)]

same_first = 4

new_lst = list(filter(lambda e:e[0]==same_first,lst))
print(new_lst)

Or Make a function.

lst = [(0, 2), (1, 2), (2, 2), (2, 3), (3, 5), (4, 5), (4, 6), (4, 7)]

def same(lst,same_number,choice):
    return list(filter(lambda e:e[choice]==same_number,lst))
    
# change choice to 0 for first and 1 for second 
print(same(lst=lst,same_number=2,choice=1)) # [(4, 5), (4, 6), (4, 7)]

print(same(lst=lst,same_number=2,choice=1)) # [(0, 2), (1, 2), (2, 2)]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading