I'm new to python and I'm having trouble understanding what the variable before the 'for' in this return statement does. I've got a slightly modified version of this code from this question
word = "boom"
def find_all(word, guess):
return [i for i, letter in enumerate(word) if letter == guess]
I understand that the function is getting every occurence of the user's guessed letter in the word "boom", creates 'i' for index and 'letter' for the value that the enumerate function is about to give. The end is stating this will happen if the letter in the word is equal to the guess in the word.
What does the
i for i
do though? I cannot find anything on it, and when I take it out it breaks the code. Is there anyway way to write this not in the return?
My modified code then later on states
board = "_" * len(word)
listed_board = list(board)
while board != word:
guess = input("Input a letter here ").lower()
if guess in word:
indices = find_all(word, guess)
print(indices)
listed_board = list(board)
for i in indices:
listed_board[i] = guess
board = "".join(listed_board)
print(listed_board)
The only other part I don't understand is when it's saying
listed_board[i] = guess
What is this doing? On the listed_board it is only underscores at this point, so how is it locating the correct position to insert the word and setting it to the user's guess?
Appreciate the replies, thanks!
Ok so here is how your code works:
word = "boom"
def find_all(word, guess):
return [i for i, letter in enumerate(word) if letter == guess]
enumerate(word)
creates new iterable object. Each letter from 'boom'
gets its own idex: [(0, 'b'), (1, 'o'), (2, 'o'), (3, 'm')]
.
Now for
loop iterate through this new object, where i
is equal to index (number from the list above), and letter
(variable) is equal to the letter (value from the list). Therefore this function will return a list of the index(s) for your guess. If the guess is equal 'b'
it will return [0]
, for 'o'
it will be [1, 2]
, for 'm'
, [3]
, else this list will be empty.
Going further:
while board != word:
guess = input("Input a letter here ").lower()
if guess in word:
indices = find_all(word, guess) # This will return all index where 'guess' is equal to letter from world. For example for word='foo', guess='o' it will return [1,2]
print(indices)
listed_board = list(board)
for i in indices: # for each index you have found:
listed_board[i] = guess # replace '_' with correct letter (guess)
board = "".join(listed_board) # change list to string
print(listed_board)
Hope this code is more obvious to you right now.