I am doing a little development, and I need to have the position of the repeated elements of a list.
What I have done for this is the following:
FDE = [1,2,3,4,4,3]
for k in range(6):
m=[i for i,x in enumerate(FDE) if x==FDE[k]]
print(m)
The result that the screen shows me is:
m=[2.5]
In short, it only looks for the repeated one '3'
but not the '4'
one that is also repeated , ideally it would print :
m=[2,3,4,5]
There are several ways to do it, one of them is to use the method
count
to see if an element is found more than once in the list. It is not the most efficient but it is concise:Departure:
Edition:
As I have told you, one option to know the value associated with the indices is to use a dictionary that has each unique duplicate element as its key and a list with the indices where it is found as its value.
Again there are several options, a relatively simple one is to use
collections.defaultdict
. We create a dictionary that stores the unique elements as keys and their indices as values, then we keep those pairs that have more than one index:Departure:
Here is a modification of the great solution given by @FJSevilla that can run a bit faster, since it removes a loop
for
in exchange for creating an objectCounter
from the list, which gets a dictionary with the number of occurrences (values ) for each element of the list (keys).As output you get both a dictionary with the indices per element, and a list with the indices of the repeated elements.