+ 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

14 Antworten

+ 7

Sure! It is correct and clear...
Just replace all slashes with double slashes, so the result will be integers

+ 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.

+ 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.

+ 4

Thanks to all

+ 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

+ 3

The answer is easier than that:
print(len(items)//2)
Hope i helped

+ 1

items = [2, 4,6,8, 10, 12, 14]
num = len(items) // 2
print(num)

0

How many elements will this slice return if the "names" list contains 5 items?
names[1:-1]

0

list="names"
print(list[1:-1])
answer: ame

0

list="names"
print(list[1:-1])
answer: 3

0

3

0

How many elements will this slice return if the "names"list contains 5items?
names[1:-1]

- 1

How many elements will this slice return if the "names" list contains 5 items?
names[1:-1]

- 5

answer