1

For some reason I keep getting index out of range error for the following code! All I want to do is compare the next data item to current one to check redundancy.

count =  0
for row2 in data2:
    count = count +1
    if data2[count][0]!=row2[0]:
       data3.append(row2)
1
  • how many items are in your data2? Commented Apr 22, 2015 at 19:54

1 Answer 1

3

Then you should loop in all but the last element of data2 as follows:

for row2 in data2[:-1]:

A more compact version for your code is:

for i,j in zip(data2[:-1], data2[1:]):
    if i!=j:
       data3.append(i)

Even more compact:

data3 = [i for i,j in zip(data2[:-1], data2[1:]) if i!=j]

Or use itertools.islice and izip to avoid creating new lists:

from itertools import islice, izip

print [i for i, j in izip(islice(data2, None, len(data2) - 2), islice(data2, 1, None)) if i != j]

Use zip if using python3.

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

3 Comments

might as well go all out and use a list comp ;)
Or use itertools to avoid building more lists print [i for i,j in izip(islice(data2,None,len(data2)-1),islice(data2, 1,None)) if i != j]
@PadraicCunningham, You should post these as answer so you get credit for them. If not, you are more than welcome to improve my answer. Thanks

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.