Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect a self referencing list in python

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?

like image 269
Tanya Sah Avatar asked Sep 25 '18 03:09

Tanya Sah


1 Answers

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.

like image 173
Mad Physicist Avatar answered Oct 28 '22 03:10

Mad Physicist