What is preventing my code from verifying both statements?


#1

to_21 = [x for x in range(1,22)]
odds = to_21[::2]
middle_third = [x for x in to_21 if (x > (len(to_21) / 3)) and ( x <= (len(to_21) * 2))]

the way I expected this to run was
middle_third = [x if x i to_21 is BOTH greater than 7 AND less than or equal to 14]
instead, it returned numbers greater than 7. Can someone please explain what is preventing my code from verifying both statements?


Why does my middle_third return the wrong range of numbers?
#2

I forgot to divide by three before i multiplied by two in the less than statement. it should read " and x <= (len(to_21) / 3) * 2]"


#3

Given this is an exercise about slicing, why the complex logic?

>>> to_21 = [x for x in range(1,22)]
>>> n = len(to_21) // 3
>>> middle_third = middle_third = [x for x in to_21 if x > n and  x <= 2 * n]
>>> middle_third
[8, 9, 10, 11, 12, 13, 14]
>>> 

Even though it does work, Python slicing is much less elaborate.

middle_third = to_21[7:14]

or

n = len(to_21) // 3
middle_third = to_21[n : 2 * n]

#4

I assumed they wanted it laid out in a non-slicing way lol. slicing seemed TOO easy :smiley:


#5

Well, it is easy, but practice makes perfect, and learning a few Python shortcuts can never be a bad thing.