Learn Python 3: List Comprehensions Exercise

https://www.codecademy.com/courses/learn-python-3/lessons/learn-python-loops/exercises/list-comprehension?action=resume_content_item

In the Learn section, it lists the following code:

for word in words:
if word[0] == ‘@’:
usernames.append(word)

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:
can_ride_coaster.append(height)

[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.

Thanks

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:
2 Likes