Поиск индексов повторяющихся элементов списка
Есть список, и мне нужно знать индекс определенного элемента.
Например:
То есть в данном списке, мне нужны индексы — 0, 2, 5
![]()
Если нужны индексы именно элементов «Маша»:
![]()
Здесь можно создать словарь, в котором по ключу будут храниться список с индексами
![]()
![]()
Дизайн сайта / логотип © 2023 Stack Exchange Inc; пользовательские материалы лицензированы в соответствии с CC BY-SA . rev 2023.9.5.43611
Нажимая «Принять все файлы cookie» вы соглашаетесь, что Stack Exchange может хранить файлы cookie на вашем устройстве и раскрывать информацию в соответствии с нашей Политикой в отношении файлов cookie.
Определить повторяющиеся значения в списке в Python
Можно ли получить, какие значения являются дубликатами в списке, используя python?
У меня есть список элементов:
Я знаю, что лучший способ удаления дубликатов — set(mylist) , но можно ли узнать, какие значения дублируются? Как вы можете видеть, в этом списке дубликаты — это первое и последнее значения. [0, 3] .
Можно ли получить этот результат или что-то подобное в python? Я стараюсь избегать делать смехотворно большой условный оператор if elif .
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.
Python – Get the indices of all occurrences of an element in a list
In this article, we will be going to understand how to get all the indices of an element in a list in Python and we will also cover a few of the best approaches to do so.
Example
Find List Index of All Occurrences of an Element
Below are the topics that we will cover in this article:
- Using a Loop
- Using List Comprehension
- Using Enumerate() Function
- Using itertools module
- Using Numpy library
- Using the Python Dictionary
- Using the Panda library
Find the Index of All Occurrences of an Item Using a Loop
This method to get the indices of all occurrences of an element in a list. Here we use a for-loop to iterate through each element in the original list.
Python3
Time Complexity: O(n)
Space Complexity: O(1)
Get Index of All Occurrences of Element Using List Comprehension
This is a simple method to get the indices of all occurrences of an element in a list using list comprehension . Here we use a list comprehension to iterate through each element in the original list.
Python3
Time Complexity: O(n)
Auxiliary Space: O(1)
Find Index of All Occurrences of an Item Using Enumerate() Function
Instead of using for-loop we can use enumerate function . This function adds a counter to an iterable and returns the enumerated object. For this, we will create a list and then we will create enumerate function to get indices of all occurrences of an element in a list
Python3
Time Complexity: O(n)
Space Complexity: O(n)
Find index of All Occurrences of an Item Using Itertools Module
An itertools module is a memory-efficient tool that is useful by itself or in combination, so for this, we will use count() methods from this module which will return an iterator of evenly spaced values from the start value. For this, we will create a list, and then using comprehension with zip() we will get indices of all occurrences of an element in a list.
Python3
Time Complexity: O(n)
Space Complexity: O(n)
Get the Indices of All Occurrences of an Element Using Numpy Library
NumPy is a general-purpose array-processing package, it provides convenient ways to use arrays in Python. For this, we will create an array using numpy.array() and then get all the indices of elements in an input array when the condition is satisfied using numpy.where() methods.
Python3
Output :
Time Complexity: O(n)
Space Complexity: O(n)
Get the indices of all occurrences of an element using the Python Dictionary
A dictionary called `indices` and a list named `my_list`. It then iterates through the elements in `my_list`, storing their indices in the dictionary `indices`. For each element encountered, if it’s already a key in the dictionary, the current index is appended to its list of indices; otherwise, a new key is created with the element and its index. Afterward, the code prints the indices of the value 1 in the list. As a result, the indices of the value 1 in `my_list` (0 and 3) are displayed when the code is executed.