You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中如何判断列表所有元素是否互不相同?

How to Check if All Elements in a List Are Unique

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 → returns True (correct)
  • List = ['a', 'a', 'x', 'y']: len(set(List)) = 3, len(List) =4 → returns False (correct)
  • List = ['a', 'a', 'a', 'a']: len(set(List)) =1, len(List)=4 → returns False (correct)
  • List = ["aa", "bb", "bb"]: len(set(List))=2, len(List)=3 → returns False (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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:36:43