How can I print a middle value from my code? For example I have got fife values in my list:
list = ['one','two','three','four','fife']
How can I print a middle value from my code? For example I have got fife values in my list:
list = ['one','two','three','four','fife']
When the number of elements in the list is odd, you have an middle element and you can print it in the following way.
my_list = ['one', 'two', 'three', 'four', 'five']
mid_index = len(my_list) // 2
print(my_list[mid_index])
You can index your list by specifiying the index at the end of the variable which contains your list.
For example:
list_name = ['one','two','three','four','fife']
list_name [0] = 'one'
list_name [2] = 'three'
list_name [4] = 'fife'
Just remember that list in python are 0 indexed, so your list starts at index 0 and not 1.
I am supposing you want to get the output as three without explicitly calling list[2]
.
Here is how you do it.
print(list[len(list)//2])
if you have a list of odd length, then use
print(my_list[(len(my_list) - 1)/2]
if your list has even number of terms, then the middle will have 2 values.
print(my_list[(len(my_list))/2]
print(my_list[(len(my_list))/2 - 1]
and dont name your list as "list" as 'list' is a predefined name in python and it will mess up stuff