-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
  • `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). – Austin Apr 15 '19 at 05: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. – Sumit S Chawla Apr 15 '19 at 05: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` – Boris Verkhovskiy Apr 15 '19 at 05:21
  • Possible duplicate of [How to get list index and element simultaneously in Python?](https://stackoverflow.com/questions/2072407/how-to-get-list-index-and-element-simultaneously-in-python) – Allan Apr 15 '19 at 05:33

1 Answers1

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!
gmds
  • 19,325
  • 4
  • 32
  • 58