-2

I'm building a simple hangman game right now, and I want to be able to identify where in a list a user guesses a specific letter. For example, if the word list was [D,R,A,G,O,N] -- and the user guesses A, I want to be able to get a return that would say 4...this is my failed code so far

import random

word_list = ['red', 'better', 'white', 'orange', 'time']
hidden_list = []
selected_word = random.choice(word_list)
letters = len(selected_word)
selected_word_list = list(selected_word)
game_playing = True

print('My word has ' + str(letters) + ' letter(s).')

print(selected_word_list)

for i in selected_word_list:
    hidden_list.append('_')

while game_playing:
    print(hidden_list)
    guess = input('What letter do you want to guess?')
    if guess in selected_word_list:
        print('Nice guess!')
    else:
        print('Nope!')
scarab
  • 13
  • 1
  • 4

3 Answers3

0
# vowels list
vowels = ['a', 'e', 'i', 'o', 'i', 'u']



# index of i item is printed
for i in vowels:
    print('The index of:', i+" "+str(vowels.index(i)))
Ayoub Benayache
  • 1,046
  • 12
  • 28
0

You can use the index function of a list

e.g.

>>> word_list.index('white')
2

But if the guess is not in the list, you will get a ValueError. You need to handle this exception.

Anthony Kong
  • 37,791
  • 46
  • 172
  • 304
0

A faster alternative to list.index is you could construct a dictionary of letter: index pairs using enumerate:

yourlist = list('DRAGON')
yourdict = {letter: idx for idx, letter in enumerate(yourlist)}

guess = input('What letter do you want to guess?')
result = yourdict.get(guess.strip()) # Avoids KeyError on missing letters

if result is not None:
    print("You got it!", result)
else:
    print("Nope!")

For short lists, list.index is completely fine and you won't notice the performance gain of the dict, but for really long lists, it makes a difference:

Short List

list
python -m timeit -s 'x = list(range(50))' 'x.index(49)'
1000000 loops, best of 3: 0.584 usec per loop
dict
python -m timeit -s 'x = dict(enumerate(list(range(50))))' 'x.get(49)'
10000000 loops, best of 3: 0.0733 usec per loop

# at this level, you really won't notice the difference on a GHz processor 

Long list

list
python -m timeit -s 'x = list(range(500000))' 'x.index(490000)'
100 loops, best of 3: 4.91 msec per loop
dict
python -m timeit -s 'x = dict(enumerate(list(range(500000))))' 'x.get(490000)'
10000000 loops, best of 3: 0.0884 usec per loop

Note that for large numbers of items, dict scales really well

C.Nivs
  • 12,353
  • 2
  • 19
  • 44