Are all items in list the same?

Karen Shaeffer klsshaeffer at gmail.com
Tue Jan 8 18:11:52 EST 2019


On 08Jan2019 15:28, Dan Sommers <2QdxY4RzWzUUiLuE at potatochowder.com> wrote:

>>    >>> a = [1, 1, 1, 1, 1]

>>    >>> a[1:] == a[:-1]

>>    True

>>    >>> a == a[::-1]

>>    True

>>

>>    >>> a = [1, 2, 3, 4, 3, 2, 1]

>>    >>> a[1:] == a[:-1]

>>    False

>>    >>> a == a[::-1]

>>    True

>>

>> Looks like Peter's pretty clever after all.  :-)

>

> Except that his solution always scans then entire list. Twice.

>

> For large dissimilar lists this gets needlessly expensive in a linear
fashion

> with the length of the list.

>

> It is succinct, but wasteful.

>

I ran it with the timeit module for the specific case of a list:


tlst = [True for _j in range(int(1e8))]


# Very fast.

# all_equal(tlst) times = [9.820610110182315e-07, 9.798338289838284e-07,
9.83037088997662e-07,

#                          9.824190249200911e-07] seconds.

def all_equal(alist) -> bool:

    if len(alist) == 0 or all(i == a[0] for i in a[1:]):

        return True

    return False


# The variant: if alist == alist[::-1]:

# actually has a memory leak. And I eventually killed the process after
waiting about

# ten minutes, while watching the memory leak.

#

# This variant doesn't have a memory leak. I'm still waiting after 15
minutes. Might give up

# on it. The other solution is the way to go.

def all_equal_array_list(alist) -> bool:

    if alist == alist[:-1]:

        return True

    return False


if __name__ == '__main__':

    tae =
timeit.repeat(timeit_all_equal,repeat=4,number=1000000,globals=globals())

    print(f"all_equal(tlst) times = {[_t/1e6 for _t in tae]} seconds.\n")


    taeal =
timeit.repeat(timeit_all_equal_array_list,repeat=4,number=1000000,globals=globals())

    print(f"all_equal_array_list(tlst) times = {[_t/1e6 for _t in taeal]}
seconds.\n")



More information about the Python-list mailing list