1

I have the following list

b = [[1,2], [1,3], [2,4], [2,5], [3,4], [3,5], [4,6], [5,6]]

I want to check the condition when second element of list b is equal to its first element.

len_b = len(b);
for i in range(0, len_b):
    if b[i][1] == b[0][i]:
        print 'anything'

but, whenever I execute this I have the IndexError: list index out of range.

3
  • 3
    b[0][i] should be b[i][0] Commented Nov 26, 2014 at 9:29
  • b[1][0] == b[1][1]. If you only want to compare second element of list you don't need to iterate it. Commented Nov 26, 2014 at 9:32
  • The error has gone; but without the print statement. Commented Nov 26, 2014 at 9:37

4 Answers 4

4

Hackaholic's solutions fixes the issue but the Pythonic way to do this is to use tuple unpacking not indexing:-

>>> b = [[1,2], [1,3], [2,4], [2,5], [3,4], [3,5], [4,6], [5,6]]
>>> for x, y in b:                                              
        if x == y:
            print 'anything'
Sign up to request clarification or add additional context in comments.

Comments

4

In addition to the provided answers, there is a simple comprehension you can use to get a list of all items satisfying the criteria:

b = [[1,2], [1,3], [2,4], [2,5], [3,4], [3,5], [4,6], [5,6]]
c = [[x,y] for x, y in b if x == y]

This can be handy if you want to filter a list.

Comments

2

In your code , it should be:

b = [[1,2], [1,3], [2,4], [2,5], [3,4], [3,5], [4,6], [5,6]]
len_b = len(b)          # not need of semi-colon here
for i in range(0, len_b):      # range(len_b) is enough
    if b[i][1] == b[i][0]:     # see here
        print 'anything'

Let me introduce you with filter and lambda:

filter(lambda x:x[0]==x[1], b)

Comments

1

Fix as:

len_b = len(b);
for i in range(0, len_b):
    if b[i][0] == b[i][1]:
        print 'anything'

Sensory, you could have more pythonic way to write code, like:

for x, y in b:
    if x == y:
        print 'xxx'

Comments

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.