0

I'm a newbie on Python, and am struggling with a small piece of my code I just don't understand why it won't work.

I have list of lists, containing 3 numbers each. I want to check if the first two numbers are the same for some of the lists. Why doesn't this work? What should I do to get it work?

list=[[0, 4, 0], [1, 4, 0], [0, 3, 1], [0, 4, 1]]

sorted(list)

for i in range(len(list)-1):
  if list[i][0][1] == list[i+1][0][1]:
      print "overlap"
Léopold Houdin
  • 1,515
  • 13
  • 18
Arie Osdorp
  • 642
  • 2
  • 8
  • 17
  • 1
    bear in mind your call to `sorted` discards its result, so has no impact on the code. Perhaps you meant `list.sort()`? This will sort the list in place (i.e. operate on the original and not return a sorted copy). – Paul Rooney Sep 18 '18 at 11:12

2 Answers2

2

You are trying to access your matrix as if it would be a 3-dimensional matrix, however it's a 2-dimensional matrix.

Remove one of the indexes:

list=[[0, 4, 0], [1, 4, 0], [0, 3, 1], [0, 4, 1]]

sorted(list)

for i in range(len(list)-1):
    if list[i][0:2] == list[i + 1][0:2]:
        print "overlap"

As @Dunes pointed out, the slice operator allows you to compare the required items of your list (check out understanding python slice notation for details).

Léopold Houdin
  • 1,515
  • 13
  • 18
  • I think this is nearly what OP wants. They want to check the first two elements. So slicing to get them would be a good idea. eg. `list_[0:2]`. – Dunes Sep 18 '18 at 11:07
  • True, didn't see that in the question, I'll update my answer. – Léopold Houdin Sep 18 '18 at 11:08
  • thank you! This really helped me out, i've been struggling with this for hours but this [0:2] syntax is perfect for what I need. – Arie Osdorp Sep 18 '18 at 11:24
  • Also, I had to sort the list in another way to make it work. But without errors, I can find my way. – Arie Osdorp Sep 18 '18 at 11:25
  • See my comment on the question with regard to why that call to sorted is useless. I think the op allude to the same issue above. – Paul Rooney Sep 19 '18 at 22:18
1

You don't need that extra [1].

list[i] accesses the inner list, e.g. [0, 4, 0]

list[i][0] accesses the 1st element of that list: e.g. 0

Also, please don't use built-in names as names for your variables as the built-in (list in our case) will no longer be accessible by that name.

Chillie
  • 1,356
  • 13
  • 16
  • This isn't entirely what op wants. OP wants to see overlap printed because there are two lists that start with `[0, 4, ...]` (as opposed to three lists that start with `0`. It would also help to explain why you shouldn't use builtin names (because you can use `list` in type checking, or as a constructor or as a base class for inheritance, and overwriting the `list` name breaks that). – Dunes Sep 18 '18 at 11:12
  • @Dunes thanks for the feedback, I'll keep this in mind for future answers. – Chillie Sep 18 '18 at 11:25