How do I check if all the elements of a nested list tree are identical?
--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Game 5 Looping
--
Chapters
00:00 How Do I Check If All The Elements Of A Nested List Tree Are Identical?
00:38 Accepted Answer Score 3
00:55 Answer 2 Score 1
01:47 Thank you
--
Full question
https://stackoverflow.com/questions/6412...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #python3x #recursion
#avk47
    Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Game 5 Looping
--
Chapters
00:00 How Do I Check If All The Elements Of A Nested List Tree Are Identical?
00:38 Accepted Answer Score 3
00:55 Answer 2 Score 1
01:47 Thank you
--
Full question
https://stackoverflow.com/questions/6412...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #python3x #recursion
#avk47
ACCEPTED ANSWER
Score 3
You can recursively convert the list to a set of items and return true if the length of the overall set is 1:
def allsametree(tree):
    def to_set(tree):
        if isinstance(tree, list):
            return {item for obj in tree for item in to_set(obj)}
        return {tree}
    return len(to_set(tree)) == 1
ANSWER 2
Score 1
Another way to do it. Split it into two operations a flatten and a check that all the values are the same.
The flatten will convert a nested iterable into one of a single dimension. So [1, [[[[[2]]]]]] becomes [1,2].
Then read the first value and cycle through the rest to check they are the same as it.
Here's the code
from collections.abc import Iterable
def flatten(iterable):
    for i in iterable:
        if isinstance(i, Iterable):
            yield from flatten(i)
        else:
            yield i
def allsametree(tree):
    flat = flatten(tree)
    iterator = iter(flat)
    try:
        first = next(iterator)
    except StopIteration:
        return True
    return all(first == rest for rest in iterator)
This will work for any iterable not just lists and because it uses lazy evaluation, it will stop when it finds two values that are not equal. This saves you from doing unnecessary work. It also avoid instantiating temporary collections (lists, sets etc.) being constructed on each recursive call.
Here's a few test inputs.