Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Identify if list has consecutive elements that are equal

Tags:

python

list

I'm trying to identify if a large list has consecutive elements that are the same.

So let's say:

lst = [1, 2, 3, 4, 5, 5, 6]

And in this case, I would return true, since there are two consecutive elements lst[4] and lst[5], are the same value.

I know this could probably be done with some sort of combination of loops, but I was wondering if there were a more efficient way to do this?

like image 710
tzhu10 Avatar asked Aug 01 '16 21:08

tzhu10


People also ask

How do you know if elements in a list are equal?

You can convert the list to a set. A set cannot have duplicates. So if all the elements in the original list are identical, the set will have just one element. if len(set(input_list)) == 1: # input_list has all identical elements.

How do you check if the numbers in a list are consecutive numbers?

Add 1 to any number in the list except for the last number(6) and check if the result is in the list. For the last number (6) which is the greatest one, pick the number before it(5) and add 1 and check if the result(6) is in the list.


2 Answers

You can use itertools.groupby() and a generator expression within any() *:

>>> from itertools import groupby
>>> any(sum(1 for _ in g) > 1 for _, g in groupby(lst))
True

Or as a more Pythonic way you can use zip(), in order to check if at least there are two equal consecutive items in your list:

>>> any(i==j for i,j in zip(lst, lst[1:])) # In python-2.x,in order to avoid creating a 'list' of all pairs instead of an iterator use itertools.izip()
True

Note: The first approach is good when you want to check if there are more than 2 consecutive equal items, otherwise, in this case the second one takes the cake!


* Using sum(1 for _ in g) instead of len(list(g)) is very optimized in terms of memory use (not reading the whole list in memory at once) but the latter is slightly faster.

like image 145
Mazdak Avatar answered Oct 14 '22 23:10

Mazdak


You can use a simple any condition:

lst = [1, 2, 3, 4, 5, 5, 6]
any(lst[i]==lst[i+1] for i in range(len(lst)-1))
#outputs:
True

any return True if any of the iterable elements are True

like image 22
Ohad Eytan Avatar answered Oct 14 '22 22:10

Ohad Eytan