I am working through a program that requires me to determine if a list of strings is a word chain. A word chain is a list of words in which the last letter of a word is the first letter of the next word in the last. The program is to return True if the list is a word chain, and false otherwise. My code is as follows:
def is_word_chain(word_list):
for i in word_list:
if i[-1] == (i+1[0]):
result = True
else:
result = False
return result
and it returns the following error:
SyntaxWarning: 'int' object is not subscriptable; perhaps you missed a comma?
if i[-1] == (i+1[0]):
Traceback (most recent call last):
if i[-1] == (i+1[0]):
TypeError: 'int' object is not subscriptable
I am wondering how I would properly reference the next item in the list in order to execute this function.
1[0]inif i[-1] == (i+1[0]):a typo?zipis your friend. Tryzip(word_list, word_list[1:])1, because it's an int. You're trying to access the ith + 1 element ofword_list, butiisn't an enumeration of the list. If you want to do it this way you need to enumerate the list and access the next element, e.g.word_list[j + 1]. I'm not saying that this is the most effective way, but if you're learning this is something worth understanding.