I will give you a small example to see what it is happening when you remove elements from a list while you iterate over:
l = ['a', 'b', 'c', 'd', 'e', 'f']
for i, c in enumerate(l):
print('_' * 25)
print('iteration', i)
print('index value', i)
print('elemnt at index ', i, ':', l[i])
print('list length:', len(l))
l.remove(c)
print('\nafter removing an element')
print('list length:', len(l))
print('index value', i)
if len(l) > i:
print('elemnt at index ', i, ':', l[i]) # this element will not be removed
print('_' * 40)
print('list after iterateion:', l)\
output:
_________________________
iteration 0
index value 0
elemnt at index 0 : a
list length: 6
after removing an element
list length: 5
index value 0
elemnt at index 0 : b
_________________________
iteration 1
index value 1
elemnt at index 1 : c
list length: 5
after removing an element
list length: 4
index value 1
elemnt at index 1 : d
_________________________
iteration 2
index value 2
elemnt at index 2 : e
list length: 4
after removing an element
list length: 3
index value 2
elemnt at index 2 : f
________________________________________
list after iterateion: ['b', 'd', 'f']
as you can see, if you remove an element while you iterate a list you modify the size of the list and from one iteration to the other, you are jumping the next element, the for loop is increasing with one the index after each iteration expecting to grab the next element but you shrink the list with one element so the for loop is actually jumping 1 element
if you want to modify the global variable words
you can use:
def getAvailableLetters(lettersGuessed):
global words
words = [c for c in words if c not in lettersGuessed]
return ''.join([str(elem) for elem in words])
getAvailableLetters(['e', 's', 'i', 'k', 'p', 'r'])
output:
'abcdfghjlmnoqtuvwxyz'
if you only want to return the letters that are not in lettersGuessed
without modifying the global variable words
:
def getAvailableLetters(lettersGuessed):
return ''.join(c for c in words if c not in lettersGuessed)