FAQ: Learn Python: Loops - List Comprehensions

#1

This community-built FAQ covers the “List Comprehensions” exercise from the lesson “Learn Python: Loops”.

Paths and Courses
This exercise can be found in the following Codecademy content:

Join the Discussion. Help a fellow learner on their journey.

Ask or answer a question about this exercise by clicking reply () below!

Agree with a comment or answer? Like () to up-vote the contribution!

Need broader help or resources? Head here.

Looking for motivation to keep learning? Join our wider discussions.

Learn more about how to use this guide.

Found a bug? Report it!

Have a question about your account or billing? Reach out to our customer support team!

None of the above? Find out where to ask other questions here!

#3

Hi,

I solved the exercise–> [164, 170, 163, 163]. But I wanted to try to solve this also without using the list comprehension. This is my approach:

``````#second approach
heights = [161, 164, 156, 144, 158, 170, 163, 163, 157]
can_ride_coaster = []

for height in heights:
if height > 161:
can_ride_coaster.append(height)
print(can_ride_coaster)
``````

Output is:

[164]
[164, 170]
[164, 170, 163]
[164, 170, 163, 163]

How can I get the output of only:
[164, 170, 163, 163]

with my code? Any hints?

#4

@code_colt
Prints each iteration on screen since print is inside the for loop.
It writes print out of the for loop and then of the same one being identado to the level of the other written lines, for example:

It will result:

[164, 170, 163, 163]

Greetings and successes to you!

Note: the English language is not my native language, sorry for some involuntary error of grammar.

3 Likes
#5

Hi there, I have a question about the example before the exercise.
Why does the example use after an element in the list:
for word in words:
if word[0] == ‘@’:
usernames.append(word)

Is it because it’s a way to check the string in the list elements?

3 Likes
#6

the examples also shows the result:

``````>>>print(usernames)
["@coolguy35", "@kewldawg54", "@matchamom"]
``````

which could help use deduce what happens.

`word` are elements of the list, `word[0]` will give us the first letter. Apparently, usernames start with a `@`

2 Likes
#7

Hello there,
Can someone help me to walk through the logic behind the syntax for list comprehension using the example before exercise? I have hard time understanding why we need to enter temporary variable `word` in front of the for loop?

``````words = ["@coolguy35", "#nofilter", "@kewldawg54", "reply", "timestamp", "@matchamom", "follow", "#updog"]
usernames = [**word** for word in words if word[0] == '@']
``````

Per example, it says that this list comprehension:

1. Takes an element in `words` -> I I understand that this happens via the for loop:
`for word in words`
2. Assigns that element to a variable called `word` -> I understand that this happens with every for loop when it assigns the value of the element it has found in the list to a temporary variable that we call here `word`

This is where I get stuck as I do not understand why we have to write `word` again in code before the for loop? What program “sees” when it hits this and why it can not run the code without it?
Thank you for the logic behind it!

#8

lets look at the example:

``````words = ["@coolguy35", "#nofilter", "@kewldawg54", "reply", "timestamp", "@matchamom", "follow", "#updog"]
usernames = []

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

the `word` variable in your question about list comprehension is equivalent to `.append(word)`

so its what we are appending to the list, this can be quite handy, for example:

``````result = [x ** 2 for x in range(1, 11) if x% 2 == 0 ]
``````

this will give us the exponents of all even numbers from 1 till 11.

so we can manipulate what we append to the list, quite useful. Hope this helps

3 Likes
#9

Thank you for your prompt attention and excellent example - I get it now!

split this topic #10

3 posts were split to a new topic: Description problems in course material

#11

words = ["@coolguy35", “#nofilter”, “@kewldawg54”, “reply”, “timestamp”, “@matchamom”, “follow”, “#updog”]
usernames =

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

One question: so each letter or number of an index has its own index? i mean the word variable is for all the things in the words list. by putting [number] next to it we check the character in that index position of an index?

#12

no, look at what word is:

``````for word in words:
print word
``````

its a string, strings do have indexes

#13

yeah i meant a string, thats what i meant but i described it very poorly. Anyway thanks u answered to my question

#14

so how the index work in strings?
if I type word[1] will it return “c”,“k”,"m"which are the second letter in those strings?

1 Like
#15

Correct. The second character element in a string is at index `1`.

The index can be positive or negative, depending which direction we are traversing the string, `left to right` (positive indices or zero), or `right to left` (negative indices, excluding zero).

``````nonsense = "supercalifragilisticexpialidocious"
``````

The positive indices, including zero will range from `0` through to `len(nonsense) - 1`. The negative indices will range from negative `len(nonsense) to`-1`.

By this we can say that the last character element in the string can be found at both,

``````nonsense[len(nonsense) - 1]
``````

and at,

``````nonsense[-1]
``````

In general,

``````n = len(nonsense)
``````

and `x` being an index is in range if it meets with this inequality…

``{ x | -n <= x < n ; x and n are int }``
#16

So, if we wanted to express it in a more general way, can we say that every string (which consists of letters/symbols/numbers) is actually a list and this list’s items are each letter/symbol/number of the string with its own index?
Using for example the word(string) ‘follow’, can we think of this string like it is the list [f,o,l,l,o,w,] ?

#17

In a sense, yes.

``````>>> list('string')
['s', 't', 'r', 'i', 'n', 'g']
>>>
``````

Both string and list objects have an `__iter__` method (only in Python 3), but only lists are mutable, not strings. We can access the characters of a string as READ ONLY, unlike lists where we can both read and write to any element, or insert, append, extend or delete an element.

Their indices work exactly the same way in both cases.

In Python 2, strings are not classed as iterable, but that version is soon to be in our rear view mirror with support likely ending within the next year.

1 Like