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"
1
  • 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). Commented Sep 18, 2018 at 11:12

2 Answers 2

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).

Sign up to request clarification or add additional context in comments.

5 Comments

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].
True, didn't see that in the question, I'll update my answer.
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.
Also, I had to sort the list in another way to make it work. But without errors, I can find my way.
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.
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.

2 Comments

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 thanks for the feedback, I'll keep this in mind for future answers.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.