2

I want to iterate through a list and want to compare the elements of list. For example: First element will be compared with next element. I've a list a:

for i in range(len(a))
    for i+1 in range(len(a)) #check code
        if a[i] == a[i+1]
           a.pop(i+1)

Can anybody suggest how to do this in python?

3
  • 2
    What, exactly are you trying to accomplish? What is your expected output? Commented Sep 9, 2017 at 3:26
  • Are you just looking to remove consecutive duplicates? Commented Sep 9, 2017 at 3:35
  • Possible duplicate of How do I remove consecutive duplicates from a list? Commented Sep 9, 2017 at 14:55

4 Answers 4

2

You are not iterating over the list by element (i.e. for el in a), that is a good thing because I believe modifying a list over which you are iterating wouldn't work. However your approach still has a flaw, in the sense that a number of elements len(a) is calculated at the beginning of the loop and the index doesn't keep into account the fact that you are removing elements, so the inspected element will refer to the position in the list after the pop (skipping elements and exceeding list length). Your example rewritten in a quite straightforward way using a temporary list b:

a=[1,3,3,6,3,5,5,7]

b=a[0:1]
for i in range(len(a)-1):
    print (a[i],a[i+1])
    if a[i]!=a[i+1]:
        b.append(a[i+1])
a=b

Or a one line version:

from itertools import compress
list(compress(a,[x!=y for x,y in zip(a[:-1],a[1:])]))

Anyway if your purpose was to remove consecutive duplicate items in a list, you could easily search on google or on stack overflow 'python remove consecutive duplicates from a list'.

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

Comments

1
for this, next_one in zip(a, a[1:]):
    compare(this, next_one)

1 Comment

dont use 'next': Assignment to reserved built-in symbol: next
0

Starting with the second element, compare each element to its predecessor.

for ix in range(1, len(a)):
    compare_items(a[ix], a[ix - 1])

Comments

0

This solution is another alternative that may work for someone facing a similar problem

for i in range(len(nums)):
    for j in range(i+1, len(nums)):
        # Then the operation you want to carry out, e.g below
        if nums[i] + nums[j] == target:
            return(i,j)

where nums is the name of the list you are iterating through,i and j are the two items you want to compare

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.