Найти повторяющиеся элементы в списке Python
В этом посте мы обсудим, как найти повторяющиеся элементы в списке в Python.
1. Использование index() функция
Простое решение состоит в том, чтобы выполнить итерацию по списку с индексами, используя понимание списка, и проверить наличие другого вхождения каждого встреченного элемента, используя index() функция. Временная сложность этого решения будет квадратичной, а код не обрабатывает повторяющиеся элементы в выводе.
Поиск уникальных и повторяющихся элементов в списке в Python
Чтобы найти уникальные элементы списка, вы можете воспользоваться набором в Python или использовать цикл for и перебирать, чтобы проверить, является ли элемент уникальным или нет.
Элемент считается уникальным, если он встречался в списке только один раз.
В этом руководстве мы напишем примеры программ, которые помогут нам найти уникальные элементы списка.
Пример 1: с помощью набора
Список в Python – это упорядоченный набор элементов, с разрешенными дубликатами.
Set – это набор уникальных элементов. Мы можем использовать это свойство, чтобы получить только уникальные элементы списка.
Передайте список в качестве аргумента конструктору набора, и он вернет набор уникальных элементов.
В следующей программе мы возьмем список чисел и создадим из него набор с помощью конструктора набора.
В получившийся набор попали только уникальные элементы.
Пример 2: с помощью цикла For Loop
Мы также можем использовать оператор цикла, например While Loop или For Loop, для перебора элементов списка и проверки того, появился ли элемент только один раз.
В следующей программе мы будем использовать вложенный цикл for, который предназначен для проверки уникальности каждого элемента. Внутренний цикл for предназначен для сравнения этого элемента с собранными уникальными элементами.
- Прочтите или возьмите список myList.
- Инициализируйте пустой список uniqueList.
- Для каждого элемента:
- Предположим, что этого элемента нет в myList – инициализировать itemExist значением False.
- Для каждого элемента x в uniqueList:
- Проверьте, равен ли элемент x. Если да, то этот элемент уже есть в вашем uniqueList. Установите для itemExist значение True и прервите цикл.
- Предположим, что этого элемента нет в myList – инициализировать itemExist значением False.
- Для каждого элемента x в uniqueList:
- Проверьте, равен ли элемент x. Если да, то этот элемент уже есть в вашем uniqueList. Установите для itemExist значение True и прервите цикл.
- Если itemExist имеет значение False, добавьте элемент в uniqueList.
- Проверьте, равен ли элемент x. Если да, то этот элемент уже есть в вашем uniqueList. Установите для itemExist значение True и прервите цикл.
Преимущество этого процесса в том, что порядок уникальных элементов не меняется.
Поиск повторяющихся элементов в списке
Чтобы найти только повторяющиеся элементы в списке в Python, вы можете проверить вхождения каждого элемента в списке и добавить его в дубликаты, если количество вхождений этого элемента больше одного.
Элемент считается дублированным, если он встречается в списке более одного раза.
В этом руководстве мы напишем примеры программ, которые помогут нам найти повторяющиеся элементы в списке.
Пример 1
В следующей программе мы возьмем список чисел и создадим из него набор с помощью конструктора набора.
How To Check For Duplicates in a Python List — Codefather

Are you writing a Python application and do you need to check for duplicates in a list? You are in the right place, let’s find out how to work with duplicates.
There are several approaches to check for duplicates in a Python list. Converting a list to a set allows to find out if the list contains duplicates by comparing the size of the list with the size of the set…

Written by Claudio Sabato
I’m a Software Engineer and Programming Coach. I want to help you in your journey to become a Super Developer!
Find Duplicates in a Python List

In this tutorial, you’ll learn how to find and work with duplicates in a Python list. Being able to work efficiently with Python lists is an important skill, given how widely used lists are. Because Python lists allow us to store duplicate values, being able to identify, remove, and understand duplicate values is a useful skill to master.
By the end of this tutorial, you’ll have learned how to:
- Find duplicates in a list, as well as how to count them
- Remove duplicates in Python lists
- Find duplicates in a list of dictionaries and lists
Let’s get started!
Table of Contents
How to Find Duplicates in a List in Python
Let’s start this tutorial by covering off how to find duplicates in a list in Python. We can do this by making use of both the set() function and the list.count() method.
The .count() method takes a single argument, the item you want to count, and returns the number of times that item appears in a list. Because of this, we can create a lists comprehension that only returns items that exist more than once. Let’s see how this works and then break it down a bit further:
Let’s break down what we did here:
- We used a list comprehension to include any item that existed more than once in the list
- We then converted this to a set to remove any duplicates from the filtered list
- Finally, we converted the set back to a list
In the next section, you’ll learn how to find duplicates in a Python list and count how often they occur.
How to Find Duplicates in a List and Count Them in Python
In this section, you’ll learn how to count duplicate items in Python lists. This allows you to turn a list of items into a dictionary where the key is the list item and the corresponding value is the number of times the item is duplicated.
In order to accomplish this, we’ll make use of the Counter class from the collections module. We’ll then filter our resulting dictionary using a dictionary comprehension. Let’s take a look at the code and then we’ll break down the steps line by line:
Let’s break this code down, as it’s a little more complex:
- We import the Counter class from the collections library
- We load our list of numbers
- We then create a Counter object of our list and convert it to a dictionary
- We then filter our dictionary to remove any key:value pairs where the key only exists a single time
In the next section, you’ll learn how to remove duplicates from a Python list.
How to Remove Duplicates from a List in Python
Removing duplicates in a Python list is made easy by using the set() function. Because sets in Python cannot have duplicate items, when we convert a list to a set, it removes any duplicates in that list. We can then turn the set back into a list, using the list() function.
Let’s see how we can do this in Python:
To learn about other ways you can remove duplicates from a list in Python, check out this tutorial covering many different ways to accomplish this! In the next section, you’ll learn how to find duplicates in a list of dictionaries.
How to Remove Duplicates in a List of Dictionaries in Python
Let’s take a look at how we can remove duplicates from a list of dictionaries in Python. You’ll often encounter data from the web in formats that resembles lists of dictionaries. Being able to remove the duplicates from these lists is an important skill to simplify your data.
Let’s see how we can do this in Python by making using a for a loop:
This method will only include complete duplicates. This means that if a dictionary had, say, an extra key-value pair it would be included.
How to Remove Duplicates in a List of Lists in Python
We can use the same approach to remove duplicates from a list of lists in Python. Again, this approach will require the list to be complete the same for it to be considered a duplicate. In this case, even different orders will be considered unique.
Let’s take a look at what this looks like:
What we do here is loop over each sublist in our list of lists and assess whether the item exists in our unique list. If it doesn’t already exist (i.e., it’s unique so far), then it’s added to our list. This ensures that an item is only added a single time to our list.
Conclusion
In this tutorial, you learned how to work with duplicate items in Python lists. First, you learned how to identify duplicate elements and how to count how often they occur. You then learned how to remove duplicate elements from a list using the set() function. From there, you learned how to remove duplicate items from a list of dictionaries as well as a list of lists in Python.
Being able to work with lists greatly improves your Python programming skills. Because these data structures are incredibly common, being able to work with them makes you a much more confident and capable developer.
To learn more about the Counter class from the collections library, check out the official documentation here.