Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use if in this list comprehension

Tags:

python

For an array of numbers, I must use list comprehension to find elements that:

  1. Are divisible by 6

  2. Their position is also divisible by 6

For example if the input is:

6 12 8 9 1 18

The output should be:

18

Here's what I have already done.

print(list(map(int, input().split()))[5::6])

I don't know how to find numbers that are divisible by 6.

like image 467
shadi Avatar asked Dec 31 '22 15:12

shadi


1 Answers

That's how you can do it:

[el for idx, el in enumerate(lst) if idx % 6 == 0 and el % 6 == 0]

Note that typically indexes start from 0 and so the correct answer is 6, not 18. If you want to index from 1 then tweak the above:

[el for idx, el in enumerate(lst, 1) if idx % 6 == 0 and el % 6 == 0]
like image 88
freakish Avatar answered Jan 22 '23 04:01

freakish