DEV Community

Cover image for Python challenge_15
Mahmoud EL-kariouny
Mahmoud EL-kariouny

Posted on

Python challenge_15

All equal

Define a function named all_equal()
that takes a list and checks whether all elements in
the list are the same.

For example:
calling all_equal([1, 1, 1]) should return True.

Challenge URI

My solution

def all_equal(equal_list):

    result = all(element == equal_list[0] for element in equal_list)

    if (result):
        return True
    else:
        return False
print(all_equal([1, 1, 1]))
Enter fullscreen mode Exit fullscreen mode

Aother solution

def all_equal(items):
    for item1 in items:
        for item2 in items:
            if item1 != item2:
                return False
    return True
Enter fullscreen mode Exit fullscreen mode

All the best to you.

Top comments (3)

Collapse
 
thejourneyville profile image
benny

Nice challenge. May I add another solution using set()? I like to use it combined with equality operator:


def all_equal(nums):
    return len(set(nums)) == 1

Enter fullscreen mode Exit fullscreen mode

Have a good one! :)

Collapse
 
mahmoudessam profile image
Mahmoud EL-kariouny

Nice solution 👌 Benny

You are the best

Collapse
 
cyzy666 profile image
Cyzy666

Could be wrong, but does this work? If everything in the list is identical, then the first number (or any number in the list, for that matter) must represent all numbers in the list.

def all_equal(series):
    return series.count(series[0]) == len(series)
Enter fullscreen mode Exit fullscreen mode