I created this code to find the middle element's index of any list . | Sololearn: Learn to code for FREE!
+ 2

I created this code to find the middle element's index of any list .

If the number of element's is an even number it will show index number of two middle elements and if it is an odd number it will show the middle element's index number Is this code correct ? Is there any other easy method ? Help me Ôś║´ŞĆ https://code.sololearn.com/cg1b850Jg0CL/?ref=app

30th Sep 2020, 5:45 AM
roshan roy
14 Antworten
+ 7
Sure! It is correct and clear... Just replace all slashes with double slashes, so the result will be integers
30th Sep 2020, 6:01 AM
Bilbo Baggins
Bilbo Baggins - avatar
+ 8
def mid(arr) : if len(arr) <3: return arr return mid(arr[1:-1]) print(mid([1,3,5,7,78,5,8,6])) find middle wirhout index.
30th Sep 2020, 6:28 AM
Oma Falk
Oma Falk - avatar
+ 6
Never use built-in names as variable names. list is the name of the base class of all list intances and you should never use that name as identifier. When the list is empty wrong indeces are shown but the code works perfectly otherwise. There are shorter and less redundant ways to write that code, but yours isn't bad. Also follow Bilbo Baggins' advice.
30th Sep 2020, 6:09 AM
Kevin Ôśů
+ 4
Thanks to all
30th Sep 2020, 7:19 AM
roshan roy
+ 3
You can take advantage of the fact that integer division // returns the same value for two consecutive numbers. To simplify your code, you can check this example. I am not sure why you need the actual indices. If you want the middle elements, you can also directly slice a list using similar formula. https://code.sololearn.com/ciO4voCEXpOZ/?ref=app
30th Sep 2020, 6:09 AM
Tibor Santa
Tibor Santa - avatar
+ 3
The answer is easier than that: print(len(items)//2) Hope i helped
23rd Apr 2021, 12:38 AM
garrigo
garrigo - avatar
+ 1
items = [2, 4,6,8, 10, 12, 14] num = len(items) // 2 print(num)
17th May 2022, 4:12 AM
Najwan Najmussabah
0
How many elements will this slice return if the "names" list contains 5 items? names[1:-1]
30th Mar 2022, 2:03 PM
C.D.D.Fernando
0
list="names" print(list[1:-1]) answer: ame
18th Nov 2022, 10:49 PM
Sergii Ponomarenko
0
list="names" print(list[1:-1]) answer: 3
14th Mar 2023, 9:42 AM
Afaq Ahmad
0
3
1st May 2023, 4:36 PM
Dharmendra Kumar
Dharmendra Kumar - avatar
0
How many elements will this slice return if the "names"list contains 5items? names[1:-1]
8th Jul 2023, 4:02 AM
Mahesh Kumar
Mahesh Kumar - avatar
- 1
How many elements will this slice return if the "names" list contains 5 items? names[1:-1]
6th Aug 2022, 3:28 PM
Uzma Jath
Uzma Jath - avatar
- 5
answer
11th Apr 2022, 7:17 PM
Gelan Solomon