 # FAQ: Code Challenge: Lists - Middle Item

#26

The `int()` function is a constructor that creates an `int` instance object. When to use it depends upon what data type will be expected in the circumstance. This is one…

``````lst[len(lst)/3] + lst[len(lst)/2]
``````

In Python 3, division results in a quotient of type, `float`. However, above we are subscripting a list which requires integer index references. Floats cannot be used as indices.

#27

I have a question about this line of code: sum = lst[int(len(lst)/2)] + lst[int(len(lst)/2) - 1]

Why is word “sum” white? Normally when I assign variables some sort of value, the name of the variable is red. Is this a special function of some sort?

#28

The editor is telling you that the name, `sum` is already taken. It’s not a safe practice to use the names common to the standard library (or any modules).

``````>>> sum([1,2,3,4,5,6,7,8,9])
45
>>>
``````

We see that it is a built in function for adding up a list of numbers.

Best advice, when you see white, change the name or add a letter or two.

``my_sum = ...``
#29

Hey All,

Can’t quite figure out why I’m still getting the integer, not float error here…

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

#30

If this is Python 3.x then it will give a float result to the division by 2. Skip all the integer casting on the components. Get to the end of the math and cast it then.

#31

Thanks for the response! By “Get to the end of the math and cast it then.” Do you mean casting the entire line as an int? e.g.

instead of:

``````lst[int(len(lst)/2) + int(len(lst)/2 - 1)/2]
``````

Do:

``````int(lst[len(lst)/2 + len(lst)/2 - 1/2])
``````

What eventually worked for me was…
(1) creating a variable that summed the two components I previously summed as one argument of the lst
(2) adding in “return” after the “else” I missed that before

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

thanks!

1 Like
#32

Have we learned int concatenation in this course yet?. Maybe I’m wrong but I thought we only learned str concatenation so far.

#33

There is no such concept as int concatenation. int is not treated as character data but as numeric. We add numbers, and concatenate character sequences (strings).

`````` "string" + " concatenation" => "string concatenation"
``````

What may appear as concatenation in the above post is actually addition of two numbers, even though they don’t look like it. Their expressions boil down to two numbers added together to give an index.

#34

Oh thats my mistake I meant int casting

#35

Consider it not unlike str casting.

``````123 => str(123) => '123'

'123' => int('123') => 123
``````

We can also use the constructor to reduce floats to ints…

``123.4 => int(123.4) => 123``
#36

Ah yes I understand it now. My issue was that I couldn’t solve the problem without that information so maybe it should be part of the course before this question. Thank you though I get it now!

#37

Where does this challenge fit in to the course flow (i.e., which units precede this)?

Consider challenges as a way to determine how ambitious a learner has been leading up to them. It is not uncommon for new concepts to arise during the solving of a problem. On the whole, there is no crime in skipping the challenge until later if one feels there is too much missing information.

#38

This is at the end of Learn Python: Lists. Oh I see, I thought the course was intended to be learned in order. I see that the hint explains a bit about int casting but it does not explain how it chops off the decimal (instead of maybe rounding for example) which was confusing for me. I personally don’t see much benefit in being given problems I don’t have the tools to solve but you are totally right that I could just skip it and come back later. I will do that for any later problems. Thank you again for helping and replying so quickly.

1 Like
#39

I don’t understand why I’m getting an error here (see attached screenshot). The error seems to be about the fact that the indices of a list cannot be floats. However, my second if statement specifies that the code that follows is for indices divisible by two with zero remainder, so they should not result in a float. I don’t understand why my code didn’t work; what am I missing?

#40

In Python 3, all division yields a float quotient.

``````>>> 6 / 2
3.0
>>>
``````

Aside

When we see a lot of repetition in the code it becomes evident that abstracting away that code makes everything a lot clearer.

``````def middle_element(lst):
if ___ % 2:
return lst[___]
else:
return (lst[___] + lst[___]) / 2
``````

Above we can see the gist of the function with repeated elements removed. Note that `len(lst)` is repeated five times in your code. We can abstract away that expression by assigning its output to a variable.

``````n = len(lst)
``````

Run once, use the result multiple times. Notice also how many times your code divides by 2? That operation can also be abstracted away.

``````m = n / 2
``````

As we know that will produce a float quotient but we can cast that to an integer with the `int()` constuctor.

``````m = int(n / 2)
``````

For odd length lists `m` will be the middle index.

``````[ ] [ ] [ ] [m] [ ] [ ] [ ]
``````

For an even length list `m` will be the lowest index in the upper half of the list.

``````  lower half      upper half
[ ] [ ] [ ] [ ] [m] [ ] [ ] [ ]
``````

That means the other middle element in the pair is at index `m - 1`.

``````    [ ] [ ] [ ] [m-1] [m] [ ] [ ] [ ]
``````

This is enough information for us to fill in the blanks in our model…

``````    if  n  % 2:
return lst[ m ]
else:
return (lst[ m - 1 ] + lst[ m ]) / 2    # will be a float
``````

When we plan ahead, the work gets lighter and mistakes are reduced to a minimum.