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

How can I make this try – except simplier in python?

this is my code:

try:    
    my_list.remove((gy,gx))
except:
    pass

I don’t need to do anything in except. Because I only want to ignore the possibility of (gy,gx) is not in the list

But now it seems the code is not beautiful enough

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

I need to make a quickly code. So i did not think about using if.

But i cannot think out any other ideas.


This code need to be repeated for hundreds of time. It need high speed.

I am wondering if "try except" is the quickiest way or there are some other way to do it quicker?


this question is much different from the question above. Because i am asking which is the quikest instead of how can i do!

>Solution :

You can use list find() method. find() takes a parameter that you want to check if it is in the corresponding list or not if your (gy, gx) tuple is not in the list then it returns -1 else returns the index of that tuple in the list.If gx and gy is numeric value, it is good practice to check sorted form of them if the order of items doesn’t matter for example:
tuple(1,2) and tuple(2,1) looks like the same objects but it is different and their memory location different too.

if my_list.find(sorted((gx, gy))) != -1:
    my_list.remove(sorted((gx, gy)))
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