-5

please help with the issue. I need to compare an element of a loop with a previous element in python 3. The code below gives the error:

TypeError: 'int' object is not subscriptable

for index, (i, j) in enumerate(zip(a_list, b_list)):
    if j[index] == j[index-1]:
        a = 0
4
  • j is element which can be int. So it's not subscriptable. You might use list variable in place of j (btw, your requirement is not known/clear). Commented Apr 15, 2019 at 5:19
  • The following error means that you are getting an integer value in j. Check what is the value of j you are getting, It probably is an integer value. Commented Apr 15, 2019 at 5:20
  • I think you meant to do if a_list[index] == a_list[index-1]: or something. But that's obviously not going to work for the first element, since a_list[0 - 1] is going to look at the last element of a_list Commented Apr 15, 2019 at 5:21
  • Possible duplicate of How to get list index and element simultaneously in Python? Commented Apr 15, 2019 at 5:33

1 Answer 1

4

i and j are elements of a_list and b_list, and therefore they are not lists which you can access with [], but rather, simple ints (presumably).

Why not do this?

data = [1, 2, 2, 3, 4, 5, 5, 5, 3, 2, 7]

for first, second in zip(data, data[1:]):
    if first == second:
        print('Got a match!')

Output:

Got a match!
Got a match!
Got a match!
Sign up to request clarification or add additional context in comments.

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.