Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python getting duplicate elements from a list

Python getting duplicate elements from a list

Document Object Reference Manual Python3 Examples

We can get duplicate elements from a list by using Python's set and list. A set is an unordered collection of unique elements, so we can use the properties of sets to find duplicate elements in a list.

Example

def

find_duplicates

(

lst

)

:

    seen

=

set

(

)

    duplicates

=

set

(

)

   

for

item

in

lst:

       

if

item

in

seen:

            duplicates.

add

(

item

)

       

else

:

            seen.

add

(

item

)

   

return

list

(

duplicates

)

Example list

my_list

=

[

1

,

2

,

3

,

2

,

4

,

5

,

3

,

6

,

7

,

8

,

7

]

print

(

find_duplicates

(

my_list

)

)

Code analysis:

  1. find_duplicates The function takes a list lst as its argument.
  2. seen is a set used to store elements that have already been traversed.
  3. duplicates is a set used to store duplicate elements.
  4. Traverse the list lst for each element in:
  5. If the element is already in seen set, add it to the duplicates set.
  6. otherwise, add the element to seen set.
  7. - If the element is already in the `seen` set, add it to the `duplicates` set. - Otherwise, add the element to the `seen` set.
    1. Finally, convert duplicates set to a list and return it.

    Output result:

    Example

    [

    2

    ,

    3

    ,

    7

    ]

    This output indicates that in the example list my_list , the element 2、3 and 7 is a duplicate.

    Document Object Reference Manual Python3 Examples