Python中如何判断列表所有元素是否互不相同?
Hey there! Let's sort out your problem step by step.
First, let's break down why your current code isn't working as expected. The line len(set(list)) != 1 checks whether not all elements are the same—it doesn't verify if all elements are unique. For your test case ["aa", "bb", "bb"], the set has a length of 2, which isn't equal to 1, so it returns True—but this just means the list doesn't have identical elements across the board, not that every element is distinct. That's why it's giving you the opposite of what you want!
The Correct Approach
The simplest and most efficient way to check for all unique elements is to compare the length of the list with the length of its corresponding set. Since sets automatically strip out duplicate values, matching lengths mean there were no duplicates in the original list.
Here's the code:
def all_elements_unique(lst): return len(set(lst)) == len(lst)
Let's test this with your examples:
List = ['a', 'b', 'x', 'y']:len(set(List)) = 4,len(List) = 4→ returnsTrue(correct)List = ['a', 'a', 'x', 'y']:len(set(List)) = 3,len(List) =4→ returnsFalse(correct)List = ['a', 'a', 'a', 'a']:len(set(List)) =1,len(List)=4→ returnsFalse(correct)List = ["aa", "bb", "bb"]:len(set(List))=2,len(List)=3→ returnsFalse(matches your expected output!)
Alternative: Without Using Sets
If you prefer a method that doesn't rely on sets (for example, if your list contains unhashable elements like nested lists), you can use a loop to check for duplicates manually:
def all_elements_unique(lst): for index, item in enumerate(lst): # Check if the current item appears later in the list if item in lst[index+1:]: return False return True
This works by iterating through each element and checking if it exists in the remaining part of the list. If any duplicate is found, it returns False immediately; otherwise, it returns True after verifying all elements.
内容的提问来源于stack exchange,提问作者Sagar

