Learn Python 3: List Comprehensions Exercise


In the Learn section, it lists the following code:

for word in words:
if word[0] == ‘@’:

what exactly is the ‘[0]’ doing in this code and why does it cause an error when I try to use it with integers in the exercise? do you only need it when searching a list for strings?

for height in heights:
if height[0] > 161:

[Traceback (most recent call last):
File “script.py”, line 5, in
if height[0] > 161:
TypeError: ‘int’ object is not subscriptable]

When I remove the [0] from height, it works fine.


word is a string in a list of words. Strings are iterable which means they can be indexed. word[0] is the character at position zero in the string.

height on the other hand is a number. Numbers are not iterable so do not have indices. They are a singular value.

for height in heights:
    if height > 161: