Zameer Ahmed
Zameer Ahmed

Reputation: 63

Finding Middle point of list in Python

I am trying a simple piece of code and I couldn't get it work to find the middle point in list. Can someone guide me with logic, please. I am a newbie and I tried a few examples on StackOverflow already but it didn't work for me.

Here is the code:

lst = [1, 2, 3, 4]
midpoint= len(lst)/2
for val in lst[:midpoint]:
     print(val)

Error is:

TypeError                                 Traceback (most recent call last)
<ipython-input-67-452ff692c8fd> in <module>
----> 1 comp(lst)

<ipython-input-66-a6223c2e7902> in comp(lst)
      3 
      4     midpoint= len(lst)/2
----> 5     for val in lst[:midpoint]:
      6         print (val)

TypeError: slice indices must be integers or None or have an __index__ method

​

Upvotes: 2

Views: 4244

Answers (3)

r3t40
r3t40

Reputation: 637

Assuming list contains only numbers.

  • If len(list) is even then midpoint or median will be float.
  • If len(list) is odd then median will be integer.

I would recommend using Python numpy module that provides median function.

from numpy import median
first = [1, 2, 3, 4]    # Even number of elements
print(median(first))
# Output 
2.5

second = [1, 2, 3]    # Odd number of elements
print(median(second))
# Output
2

For Python >= 3.4 you can use statistics module where you can also find median function.

Hope this helps.

Upvotes: 1

Mudassar Hashmi
Mudassar Hashmi

Reputation: 2899

You are using Python3 and in Python 3 you need to use '//' instead of '/' like below.

midpoint= len(lst)//2

Upvotes: 3

Vashdev Heerani
Vashdev Heerani

Reputation: 679

lst = [1, 2, 3, 4]
midpoint= int(len(lst)/2)
for val in lst[:midpoint]:
     print(val)

Try this

Upvotes: 1

Related Questions