Last updated: Apr 10, 2024
Reading timeยท3 min
To find the indices of duplicate items in a list:
enumerate()
.def find_indices(l, value): return [ index for index, item in enumerate(l) if item == value ] # ๐๏ธ [0, 2, 3] print(find_indices(['one', 'two', 'one', 'one'], 'one')) # ๐๏ธ [] print(find_indices(['one', 'two', 'one', 'one'], 'abc'))
start
index, scroll down to the next subheading.We used the enumerate()
function to get access to the index of the current
iteration.
The enumerate() function takes an iterable and returns an enumerate object containing tuples where the first element is the index and the second is the corresponding item.
my_list = ['bobby', 'hadz', 'com'] for index, item in enumerate(my_list): print(index, item) # ๐๏ธ 0 bobby, 1 hadz, 2 com
On each iteration, we check if the current item is equal to the given value.
def find_indices(l, value): return [ index for index, item in enumerate(l) if item == value ]
If the condition is met, we return the corresponding index.
The list the function returns contains all indices of the value in the original list.
If you need to find the indices of the duplicate items in a list with a start index:
while True
loop to iterate until the occurrences of the item are
found.list.index()
method to get the index of each occurrence by
specifying a start
index.def find_indices(l, value, start=0): indices = [] while True: try: index = l.index(value, start) start = index + 1 indices.append(index) except ValueError: break return indices # ๐๏ธ [2, 3, 5] print(find_indices(['a', 'b', 'a', 'a', 'b', 'a'], 'a', 1)) # ๐๏ธ [3, 5] print(find_indices(['a', 'b', 'a', 'a', 'b', 'a'], 'a', 3)) # ๐๏ธ [5] print(find_indices(['a', 'b', 'a', 'a', 'b', 'a'], 'a', 4)) # ๐๏ธ [] print(find_indices(['a', 'b', 'a', 'a', 'b', 'a'], 'a', 6))
The function takes an optional start
index.
The start
index is the index at which we start looking for occurrences of the
given value in the list.
The list.index()
method returns the index of the first item whose value is
equal to the provided argument.
list.index()
method takes an optional `start`
argument and starts looking for the specified value from the start
index onwards.print(['a', 'b', 'c', 'a'].index('a', 1)) # ๐๏ธ 3
The method raises a ValueError
if there is no such item in the list.
If a ValueError
is raised, we break out of the while
loop and return the
indices
list.
def find_indices(l, value, start=0): indices = [] while True: try: index = l.index(value, start) start = index + 1 indices.append(index) except ValueError: break return indices
Otherwise, we increment the start
index by 1
and append the index to the
indices
list.
The list.append() method adds an item to the end of the list.
You can learn more about the related topics by checking out the following tutorials: