Search code examples
pythonfor-looplist-comprehensionindex-error

How to access elements using list comprehensions / double for-loops? Problem solving IndexError.


I am trying to learn list-comprehensions, and for that I am trying to print the fourth letter for each city in the following list:

word_list = ["Amsterdam", "Hannover", "Milano", "Paris", "London", "Glasgow", "Dublin", "Tokyo", "Canberra"]

I think I need a double for loop here, one to access the cities in the list, and one to access the letters of each city. However, when I try to put this inside a list comprehension like:

listcomprehension = [letter[3] for word in word_list for letter in word]
print(listcomprehension)

I get the following error:

IndexError: string index out of range

I tought it could be an error with my list-comprehension (Since I am new to those), so I tried to achieve my goal using a normal double for-loop:

for word in word_list:
    for letter in word:
        print(letter[3])

What am I doing wrong here? All cities have more than 4 letters, so I don't understand why this error is happening. I am rather new to programming, and I am still often confused when using double for-loops... Could someone enlighten me?


Solution

  • letter is already a single letter, letter[3] doesn't exist because letter only contains one letter.

    You don't need two loops because strings can be indexed.

    listcomprehension = [word[3] for word in word_list]
    

    or

    for word in word_list:
        print(word[3])