Trying to solve for the middle number in a list | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Trying to solve for the middle number in a list

I'm on exersize 25.3 "The Middle Element" and the following code works in my Python IDE but not in the app... items = [2, 4, 6, 8, 10, 12, 14] print(items[len(items) // 2])

4th Nov 2021, 2:20 AM
Kevin Taylor
Kevin Taylor - avatar
5 Answers
+ 2
Hi Kevin! As mentioned above, we don't see any error in your code. But, please double check whether they're asking you to print the middle element or its index. If its index, print(len(items)//2) will do the job.
4th Nov 2021, 2:37 AM
Python Learner
Python Learner - avatar
+ 1
It works for me in the app (output 8). What did you get as output? error message or just 'No output' # odd sized iterable odd_sized = [ 2021, 11, 4 ] iter_len = len( odd_sized ) // 2 print( f"{odd_sized} -> {odd_sized[ iter_len ]}" ) # even sized iterable even_sized = [ 12, 5, 48, 376 ] iter_len = len( even_sized ) // 2 - 1 print( f"{even_sized} -> {even_sized[ iter_len : iter_len + 2 ]}" ) # even length iterable P S. Please tag a relevant language next time https://code.sololearn.com/W3uiji9X28C1/?ref=app
4th Nov 2021, 2:30 AM
Ipang
+ 1
Solved it. It wanted to specify the index of the middle number not the actual value -_-
4th Nov 2021, 8:51 PM
Kevin Taylor
Kevin Taylor - avatar
+ 1
I realize that when len is not even and as the index is 0 based the len//2 is ok..so for your example is ok. But when is len is even...what value to to choice...lenx//2 or lenx//2-1..
5th Nov 2021, 2:56 AM
Cristian Baeza Jimenez
Cristian Baeza Jimenez - avatar
0
But what happen when the len of the list is not even, for example 3, the result considering the code above give the first element insted of the second one.. I would use // and %2..
4th Nov 2021, 4:37 AM
Cristian Baeza Jimenez
Cristian Baeza Jimenez - avatar