I have been trying to find a self-referencing loop in a list. I have referenced the list like this:
a = [1, 2, None]
a[2] = a
What is the right way to detect this loop in python?
I'm not sure if there's a "right" way, but the is
operator is your friend. To check if the list contains itself:
any(x is a for x in a)
To find the index of the list:
next(i for i, x in enumerate(a) if x is a)
This version is like a.index
in that it raises an error if the list is not found in itself. To simulate a.find
instead, add a default value to next
:
next(..., -1)
You can't use a.find
or a.index
directly because those will search by equality, which will be infinitely recursive on a positive match in this case.
Checking for identity should be relatively foolproof in this case.
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