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

List Index for lists that create a grid

I’m trying to find the index of an element in list, obviously I tried the normal list.index() method but its says that the item is not in the list (but it is). Since I’m creating a grid with this list, maybe there is an other method.

Here is the code.

grid = [[200, 200, 200, 200, 200, 200, 200], [200, 200, 200, 400, 200, 78, 200], [200, 200, 400, 400, 200, 75, 200], [200, 200, 400, 400, 300, 200, 200], [200, 300, 200, 400, 400, 200, 200], [200, 14, 200, 52, 200, 84, 200], [200, 200, 200, 200, 200, 200, 200]]

print(grid.index(200))

The error is:

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

ValueError: 200 is not in list

But I can see that grid[0][0] is 200

Hear a photo of the grid created from the list enter image description here

>Solution :

You could use the following to get a List of Tuples containing the two co-ordinates in your List of Lists:

seeking = 200
idx = [(i,j) for i, x in enumerate(grid) for j, y in enumerate(x) if y == seeking]

print(idx)

which produces

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

so (0,0) means subList 0, element 0 and so on

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