-2

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']
Hashir Malik
  • 798
  • 2
  • 9
  • 27
debek
  • 331
  • 7
  • 15
  • 1
    use indexing: `list[0]`, `list[1]` etc. (And don't call your list `list` either, that's the name of a built-in function.) – Robin Zigmond Feb 14 '19 at 17:09
  • 2
    https://www.google.com/search?q=python+access+list+element – andydavies Feb 14 '19 at 17:10
  • lst[int(len(lst)/2)] – Alex Yu Feb 14 '19 at 17:12
  • 1
    `lst[len(lst)//2]` – Olivier Melançon Feb 14 '19 at 17:13
  • 4
    Possible duplicate of [Find middle of a list](https://stackoverflow.com/questions/38130895/find-middle-of-a-list) – kHarshit Feb 14 '19 at 17:15
  • The question is a bit unclear now about what "middle" is and what you are expecting if there's an even number of items in the list. It may be helpful to [edit your question](https://stackoverflow.com/posts/54695644/edit) to include that detail and to clarify if you are asking how to access to middle element or whether you are looking how to calculated the index of the middle element so you can access it. It'd have also been good to explain attempts you've made so far and in what way they aren't working. – Jeff B Feb 14 '19 at 17:59

4 Answers4

2

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])
0

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.

Edeki Okoh
  • 1,786
  • 15
  • 27
0

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])

0

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

Shaheer Bin Arif
  • 222
  • 1
  • 3
  • 11
  • You can probably rewrite this so it checks if len(my_list) % 2 is 0 or 1 before accessing the middle element. – Edeki Okoh Feb 14 '19 at 17:16
  • A 'hacky' solution that will take even or odd lists: `list_name[int(len(list_name)/2)]` but that depends on what the 'middle' is considered on an even list. – Patrick Conwell Feb 14 '19 at 17:17
  • @EdekiOkoh yeah i could write it with the if statement but wasnt sure if the questioner would be aware of if statements as he seems new to programming – Shaheer Bin Arif Feb 14 '19 at 17:25