I need a little help with understanding, or like how to read these kind of comprehension
[word[1:-1:2] for word in ['Norway', 'Sweden', 'Denmark'] if 'r' in word]
h = [2*x for x in range(10) if divmod(x, 2)[1] == 0]
thanks in advance
I need a little help with understanding, or like how to read these kind of comprehension
[word[1:-1:2] for word in ['Norway', 'Sweden', 'Denmark'] if 'r' in word]
h = [2*x for x in range(10) if divmod(x, 2)[1] == 0]
thanks in advance
In general, go from right to left for each for
.
First example:
for word in ['Norway', 'Sweden', 'Denmark'] if 'r' in word
:
For each word that contains the letter r
word[1, -1, 2]
add word to list, with special modifications to word.
Second example:
for x in range(10) if divmod(x, 2)[1] == 0
for each x as single digit number, if the remainder of x / 2 is 0
2**x
add 2**x to list.
In more complicated, nested for loops case, this will make more sense.
[word[1:-1:2] for word in ['Norway', 'Sweden', 'Denmark'] if 'r' in word]
is equivalent to:
result = []
for word in ['Norway', 'Sweden', 'Denmark']:
if 'r' in word:
result.append(word[1:-1:2])
h = [2*x for x in range(10) if divmod(x, 2)[1] == 0]
is equivalent to:
h = []
for x in range(10):
if divmod(x, 2)[1] == 0:
h.append(2*x)
The pattern to list comprehensions is
[what to do - for loop - optional if statement]
which spans out to (exmaple 1)
output_list = []
for word in ['Norway', 'Sweden', 'Denmark']:
if 'r' in word:
output_list.append(word[1:-1:2])
and example 2:
h = []
for x in range(10):
if divmod(x, 2)[1] == 0:
h.append(2*x)