0

I have a list

A= [1,2,3,3,4,4,5,6,4,7]

I want to only keep one 3 and 4 if they are next to another identical one.

Thus A should become

A= [1,2,3,4,5,6,4,7]

I tried to use set

set[A]

{1, 2, 3, 4, 5, 6, 7}

But it removed the last 4 that I want to keep. It seems I should loop through the list and compare i and i+1. Wondering any faster and smarter way exists?

Kevin
  • 587
  • 1
  • 7
  • 17

2 Answers2

4

Using list comprehension:

[A[i] for i in range(len(A)) if (i==0) or A[i] != A[i-1]]
#[1, 2, 3, 4, 5, 6, 4, 7]

The logic is to iterate through each index in the list and keep the number if either of the following conditions hold:

  • i==0 (the first element)
  • A[i] != A[i-1]
pault
  • 41,343
  • 15
  • 107
  • 149
0

Try this:

A = [1,2,3,3,4,4,5,6,4,7]
newlist = []
newlist.append(A[0])
for i, element in enumerate(A):
    if i > 0 and A[i - 1] != element:
        newlist.append(element)

Here, we loop through the list and check that every element is not equal to the element before it. It will return

[1, 2, 3, 4, 5, 6, 4, 7]
Seth Rothschild
  • 384
  • 1
  • 14