0

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

Stuart
  • 9,597
  • 1
  • 21
  • 30
  • you can just paste these onto the python command line and try them – stark May 21 '21 at 15:16
  • If you wonder what the `word[1:-1:2]` does or means, check out this post https://stackoverflow.com/questions/509211/understanding-slice-notation – samusa May 21 '21 at 15:18
  • Or just try it: `[i for i in '123456789'[1:-1:2]]` yields `['2', '4', '6', '8']` – stark May 21 '21 at 15:19
  • i also have some trouble understanding how divmod function works – ineedsomehelp May 21 '21 at 15:25
  • @ineedsomehelp it's a slightly overly complex way of checking if the number is an even number, if the remainder after being divided by 2 is 0 – Chris May 21 '21 at 15:29

3 Answers3

3

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.

Dave N.
  • 138
  • 1
  • 8
1
[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)

0x5453
  • 12,753
  • 1
  • 32
  • 61
0

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)
Eumel
  • 1,298
  • 1
  • 9
  • 19