Introduction
In Python, a list is a collection of items that are ordered and changeable. Sometimes, we need to check if a list has any duplicate elements. In this challenge, you will write a Python function to check if a list has any duplicates.
This tutorial is from open-source community. Access the source code
In Python, a list is a collection of items that are ordered and changeable. Sometimes, we need to check if a list has any duplicate elements. In this challenge, you will write a Python function to check if a list has any duplicates.
Write a Python function called has_duplicates(lst)
that takes a list as an argument and returns True
if the list has any duplicate elements, otherwise returns False
.
To solve this problem, you can follow these steps:
def all_unique(lst):
return len(lst) == len(set(lst))
x = [1, 2, 3, 4, 5, 6]
y = [1, 2, 2, 3, 4, 5]
all_unique(x) ## True
all_unique(y) ## False
In this challenge, you learned how to check for duplicates in a list using Python. You can use this function to ensure that your lists only contain unique elements.