Irkl1_
Irkl1_

Reputation: 71

Check if content of index equals content of next index

array = [1, 1, 1, 1, 1, 1, 2]
new_array = [x for x in array if array[array.index(x)] != array[array.index(x) + 1]]
print(new_array)

Hi, I'm trying to write a program that will check if a content of an index (example: list[0]) equals to next index and if not append the number that differs and I tried to use a new skill I learned which is list comprehension and I don't quite understand why doesn't it work how it should work

To make it more clear what I mean is if I am given an array with all numbers the same except one number which in this case is two I want to append it in a list I also added a picture to make it even more clear

enter image description here

Upvotes: 0

Views: 556

Answers (3)

deadshot
deadshot

Reputation: 9061

You can use this simple one liner

print(a[0] if a.count(a[0]) == 1 else min(set(a).difference(a[:1])))

Note: I'm using min() to just to get the element from set.

Output:

>>> a=[1, 1, 2]
>>> print(a[0] if a.count(a[0]) == 1 else min(set(a).difference(a[:1])))
2
>>> a = [17, 17, 3, 17, 17, 17, 17]
>>> print(a[0] if a.count(a[0]) == 1 else min(set(a).difference(a[:1])))
3

Upvotes: 1

Saeed Ramezani
Saeed Ramezani

Reputation: 482

it may help you:

list = [1, 1, 2, 3, 4, 4]
for i, j in enumerate(list[:-1]):
    if j  == list[i+1]: 
       #dosomething

Upvotes: 0

Tugay
Tugay

Reputation: 2214

IndexError: list index out of range means you are passing an index that isn't present in the list. And that error is raised in this part:

array[array.index(x) + 1]

When x is the last element error is raised. Because there is no index after the last element. In your case, using list comprehension isn't the best choice, you should prefer for loop.

Upvotes: 1

Related Questions