Prettier way to do middle_third?


#1



https://www.codecademy.com/en/courses/python-beginner-en-KAgt5/2/5?curriculum_id=4f89dab3d788890003000096


Instead of just diong middle_third = to_21[7:14] I wanted to make some code that finds the middle third for a less specific list of numbers.

This is my attempt, which does solve the solution, but it looks messy af. So what are your suggestions to make it filll less and make it more manageable?

middle_third = [x for x in to_21 if x > (len(to_21)/3) and x < \
float((len(to_21)/3))+float((len(to_21))/3)+1]


#2

We would need to first know that the list can be evenly divided in three equal length lists.

if len(my_list) % 3 == 0:

then,

n = int(len(my_list) / 3)
x = []
while my_list:
    x.append([my_list.pop(0) for i in range(n) if len(my_list)])

print (x[1])

>>> my_list = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21]
>>> n = int(len(my_list) / 3)
>>> x = []
>>> while my_list:
    x.append([my_list.pop(0) for i in range(n) if len(my_list)])

    
>>> print (x[1])
[8, 9, 10, 11, 12, 13, 14]
>>>

#3

Thanks for the reply - and the code :slight_smile:

I would like to know how the while my_list: loop works, and not going into infinite loop. Since you pop() elements in it, does the loop stop when there is no elements in my_list?


#4

Yes, that is the exit condition.

The while loop will iterate three times in our example, each time appending a shorter list to the temporary list, x.

More to your point, which is based on slicing, again assuming the list is evenly divisible by 3,

x = [ ... ]   # long list

n = int(len(x) / 3)

At this point, n will be the index of the first element in the middle third. Times it by 2 and we get the first element in the top third (the exclusion)

print x[n:n * 2]

>>> x = [i for i in range(1, 100)]
>>> n = int(len(x) / 3)
>>> print (x[n:n * 2])
[34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66]
>>>

#5

Given that we checked or know that the list can be evenly divided in three equal length lists, then this works:

to_21 = range(1, 22)

third = len(to_21) / 3

middle_third = to_21[third : 2 * third]

I like it because it is very simple and generic.


#6

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.