I will tutor you

  • coppercrystalz [he/him]
    ·
    4 years ago

    Alright, I'm new to Python and I'm trying to make hangman in it. I convert the word picked to a list of all of it's characters then run a for loop when the player makes a guess to see if the guess is equal to any of the items in the list. If the guess is equal to a character in the list it fills that letter in in another list of underscores the same length as the original word list by taking the position of the letter in the original list and putting the guessed letter in the same position in the underscore list. This works fine except for when there are multiples of the same letter in a word, in which case only the position of the first instance of that letter is filled in in the underscore list. After going through the debugger step by step, I saw that what happens in that even when the for loop is on the second instance of the letter, only the position of the first instance is returned.

    So my question is, if there are multiple instances of the same item in a list, how do you make it so that when checking the position of the item Python returns the position of the nth instance instead of just the first?

    • Bloodshot [he/him,any]
      hexagon
      ·
      edit-2
      4 years ago

      I assume you're using array.index(char), which returns the first index. index also accepts a start argument, so ['a', 'b', 'b', 'a'].index('a', 1) will return 3.

      A bit more natural way to write this is to loop over the search list, and just check for equality, like this:

      def indices(array, search):
          indices = []
          for index, value in enumerate(array):
              if search == value:
                  indices.append(index)
      
          return indices
      

      This can be its own function or inline. Above, I use enumerate, which allows you to iterate over both the index and the value.