简体   繁体   中英

How to find the middle element/index of a list in Python?

I want to be able to print the middle element of a list . The list might be just strings, integers or mixed. I tried this, by finding the index of the middle element, but doesn't work. (It prints 2)

list = [1,3,7,"this",3,"that",7]

if int(len(list))<2:
  middle = 1  // if it has less than 2 entries, the first entry is the middle one. 

elif int(len(list)) %2 == 0 :
  middle = int(len(list)/2)

else: 
  middle = int((len(list)/2) - 1)

print(list[middle])

In case you want to round down for odd amount of list elements, you can use math.trunc for all cases:

l = [1,3,7,"this",3,"that",7]
middle = math.trunc(len(l)/2)
print(middle)
>>> 3

You cannot use list as a variable name, it is already reserved. Second, comments in python should be like this # comment not //comment .

The following code works just fine:

listt = [1,3,7,"this",3,"that", 7]
middle = int((len(listt)/2)) 
print(listt[middle])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM