lines = {} # will map so that lines[word] is a list of line numbers with open('money.txt') as lyrics: num = 0 for line in lyrics: num += 1 pieces = line.lower().split() for word in pieces: if word not in lines: lines[word] = [num] # first time this word appears elif lines[word][-1] != num: lines[word].append(num) # first time on this line for word in ('nowhere', 'the'): print(word, lines[word])