Search code examples
pythonlist

How to check how many of the last elements in a list are equal in python?


I am appending integers to a list one by one (using a loop) as so:

A.append(x) where x is an integer, which eventually gives for example:

A = [4, 8, 2, 4, 3, 7, 7, 7]

During every loop, i.e. just after each integer is added to the end of the array, I would like to check whether the same integer has been added a certain number of times (say, 3, in the example below) and throw an exception if so.

Pseudo code:

if somewayofcheckingA == 3:
    raise Exception("Lots of the latest integers are similar")

I could just do the below, but if I wanted to check for say, 100 repeats, then obviously the code would become a mess.

if A[-1] == A[-2] and A[-2] == A[-3]:
    raise Exception("Lots of the latest integers are similar")

Thanks!


Solution

  • Passing a list to set() will return a set with all unique values in the list. You can use slice notation to get a list of the last n values using the following

    n = 3
    if len(A) >= n and len(set(A[-n:])) == 1:
        raise Exception("Lots of the latest integers are similar")