Search code examples
pythonlistloopspython-itertools

Loop through list based on number of characters of user input


I am using a list to hold strings. A user inputs a message and each character is searched for in the list.

for count, letter in enumerate(newMessage):
    foundAt = myList[count].find(letter)

I'm using the count variable to access the proper element in the list but when there are more characters than elements in the list it returns an error. If I had ten elements on the eleventh character I would want it to search the first element.


Solution

  • So you just want to circle around the list as you go through it? (So if the list is 10 elements, 0-9 corresponds to 10-19, 20-29, etc.)

    You could do:

    for count, letter in enumerate(newMessage):
        foundAt = myList[count % len(myList)].find(letter)