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

Python finding duplicate elements in a list

Python finding duplicate elements in a list

Document Object Reference Manual Python3 Examples

In Python, finding duplicate elements in a list can be implemented in several ways. A common method is to use a set to store elements that have already appeared, then traverse the list and check whether each element already exists in the set. If it does, the element is a duplicate.

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

,

5

]

print

(

find_duplicates

(

my_list

)

)

Code analysis:

  1. seen is a set used to store elements that have already appeared.
  2. duplicates is a set used to store duplicate elements.
  3. Traverse the list lst, for each element item:
  4. If both the item is already in seen set, add it to the duplicates set.
  5. Otherwise, add item to seen set.
  6. - If `item` is already in the `seen` set, add it to the `duplicates` set. - Otherwise, add `item` to the `seen` set.
    1. Finally, convert duplicates set to a list and return it.

    Output result:

    Example

    [

    2

    ,

    3

    ,

    5

    ]

    Document Object Reference Manual Python3 Examples