Course Content
Python Indentation, Comments and Variables
0/2
Object Oriented Programming in Python
0/1
Exception Handling in Python
0/1
Sending emails with Python
0/1
Unit test in python programming
0/1
Python programming (zero to advance!!!)
About Lesson

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.

 

==== SOLUTION ====

By using the `set` data structure. If all elements in the list are the same, converting the list to a set should result in a set with a single element. Here’s how you can do it:

“`python
def all_equal(lst):
# Check if the set of elements in the list has a length of 1
return len(set(lst)) == 1

# Test the function
print(all_equal([1, 1, 1])) # Output: True
“`

Explanation:

1. `def all_equal(lst):`: This line defines a function named `all_equal` that takes a single parameter `lst`, which is a list.

2. `return len(set(lst)) == 1`: This line checks if the length of the set created from the elements of the list `lst` is equal to 1. If the length is 1, it means all elements in the list are the same, and the function returns `True`; otherwise, it returns `False`.

So, when you call `all_equal([1, 1, 1])`, it returns `True` because all elements in the list are equal (all equal to 1).

 

Join the conversation