How to compare the elements of a list

Asked

Viewed 26 times

0

So, I need to develop the body of a code that travels through a list already ordered to find out in which positions are the equal elements. How do I do that?

1 answer

1


I believe the code below can help you. Basically it iterates item by item in the list and identifies whether the item in a given position is equal to the previous one, since you said that your list is already sorted

lista1 = [1,2,2,3,4,5,6,6,6,6,7,8,9,10]

prev_item = lista1[0]-1 # garante que prev_item está fora da lista1

for index in range(0,len(lista1)):
    if lista1[index] == prev_item:
        print(f'valor repetido na posição {index}')
    
    prev_item = lista1[index]

outworking:

valor repetido na posição 2
valor repetido na posição 7
valor repetido na posição 8
valor repetido na posição 9
  • has the possibility to use a dictionary, returning after each position for each item searched.

  • I’ll try this one! But I forgot to mention tbm that I do not have access to the list elements, a priori (can modify according to who type). I can follow the same pattern?

  • I don’t even have access to the list itself, the part of the for forward should work, as long as you can import the list into your code.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.