FAQ: Code Challenge: Lists - Middle Item

This community-built FAQ covers the “Middle Item” exercise from the lesson “Code Challenge: Lists”.

Paths and Courses
This exercise can be found in the following Codecademy content:

Computer Science
Data Science

FAQs on the exercise Middle Item

Join the Discussion. Help a fellow learner on their journey.

Ask or answer a question about this exercise by clicking reply (reply) below!

Agree with a comment or answer? Like (like) to up-vote the contribution!

Need broader help or resources? Head here.

Looking for motivation to keep learning? Join our wider discussions.

Learn more about how to use this guide.

Found a bug? Report it!

Have a question about your account or billing? Reach out to our customer support team!

None of the above? Find out where to ask other questions here!

4 posts were split to a new topic: Why the ‘list’ command?

2 posts were split to a new topic: Why are the preceding lst required?

3 posts were split to a new topic: Why do I have to include the /2 in the int()?

2 posts were split to a new topic: Spoiler

8 posts were split to a new topic: Is middle different than median?

2 posts were split to a new topic: Flaming troll

3 posts were split to a new topic: Solution suggestions for Middle item challenge

2 posts were split to a new topic: List indexes cannot have floats [solved]

2 posts were merged into an existing topic: List indexes cannot have floats [solved]

2 posts were split to a new topic: Why is my sum variable text white? [solved]

3 posts were merged into an existing topic: List indexes cannot have floats [solved]

7 posts were split to a new topic: How does integer casting work? int() [solved]

2 posts were merged into an existing topic: List indexes cannot have floats [solved]

2 posts were split to a new topic: Challenge lists - why doesn’t this work [solved]

2 posts were merged into an existing topic: List indexes cannot have floats [solved]

3 posts were split to a new topic: Lists challenge - code problem [solved]

4 posts were merged into an existing topic: List indexes cannot have floats [solved]

I solved this by making the two scenarios into variables; even and odd. Each variable finds their respective midpoints, which makes them easy to average and call in the control flow. There’s probably a more elegant way to solve this, though, haha.

def middle_element(lst):
  even = int(len(lst)/2) - 1
  odd = int(len(lst)/2)
  if  len(lst) % 2 != 0:
    return lst[odd]
  else:
    return (lst[even]+lst[odd])/2

Rather than doing floating point arithmetic and rounding later, stick with integer operations:

# don't:
int(a / b)
# do:
a // b
1 Like