What does int() mean?


Hello, there~

I have questions regarding this:

Create a function called middle_element that has one parameter named lst .

If there are an odd number of elements in lst , the function should return the middle element. If there are an even number of elements, the function should return the average of the middle two elements.

The answer is

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

print(middle_element([5, 2, -10, -4, 4, 5]))

I have 3 questions:

  1. What does int() mean in this code?

  2. How does lst[int(len(lst)/2)] indicate the middle element?

  3. lst[int(len(lst)/2) - 1] what does - 1 indicate in this code?

Thank you for your assistance!

The built-in int() is a way of creating a new integer object from its inputs. For the given example it just creates an integer from what would otherwise be a float. You can check the details here- https://docs.python.org/3/library/functions.html#int

If len(lst) defines the length of the list then what would half of this value indicate? Using lst[idx] is a way of returning the reference of a specific index in the list lst. Since indices are integer values can you see why int is used? What happens for odd/even numbers in this case?

Once you have the statement above worked out the -1 is straightforward math which subtracts 1 from the results of the len(lst) expression. Can you work out why this necessary?

Personally I’d encourage the use of floor division // as opposed to calculating a float and then creating an integer from it. There’s also a lot of repeated function calls and such in this code and it could be simplified by evalulating it once and maintaining a reference to it-

half_lst_len = len(lst) // 2  # perhaps with a better name