How to return the indices that an element appears in a tuple?

Asked

Viewed 31 times

-2

**Write a function called 'positions' that you take as input arguments a tuple and an item, and returns a list containing all the indexes in which the item appears on tuple. If the item does not exist in the tuple, it should return an empty list. ** -MY CODE

tupla = (5, 6, 5, 3, 5)
def posicoes(tupla, item):
    indice = 0
    for i in range(len(tupla)):
      if item in tupla(i):
        indice.append((i))
    
    return indice

print(posicoes(tupla,5))
  • 1

    You are trying to use the method .append() in a variable that receives 0, where it defines the variable indice, should be indice = [].

  • po, you’re right, I forgot to change when posting

1 answer

1

To return the index of the tuple item, you can use the method enumerate(tupla), it returns the value of the tuple next to its index, so if the item equals its variable item, you only add content in the list indice

The code goes like this:

tupla = (5, 6, 5, 3, 5)
def posicoes(tupla, item):
  indice = []
  for i in enumerate(tupla):
    if i[1] == item:
      indice.append(i[0])

  return indice

print(posicoes(tupla,5))
  • good evening, Elipe, could explain why of 'if i[1] did not understand why of the 1'

  • Good evening @Viniciusmota, when you go through the tuple items with for i in enumerate(tupla):, you receive the value of i as ({índice},{valor}), and where if i[1] == item: we only want to compare the value of the tuple and not the index, and if true the condition, just add the index in the list indice with indice.append(i[0]). Test code yourself only with print(i) after for i in enumerate(tupla):

  • Ask, understand, thank you very much Thank you, thank you for your help

Browser other questions tagged

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