Find Mid in Python? Simple Way

admin
By -
0

Hey, welcome to my blog where I share some cool Python tips and tricks. Today, I want to show you how to find the middle element of a list using some simple arithmetic operations.



Let's say we have a list of numbers like this:

b = [1,2,3,4,5,6,7,8]

How can we get the middle element of this list without using any built-in functions or slicing? Well, one way is to use the first and the last element of the list and divide them by two

For This You have to knowledge or familiar with indexing or  python index.

For example:
mid  = b[0]  +  b[-1]  / 2
print(mid)

This will print 4.5 or 5.0 in my output its 5.0, which is the average of the first and the last element. But what if we want to get the exact middle element, not the average? In that case, we can use the floor division operator (//) instead of the regular division operator (/). This will round down the result to the nearest integer. 

For example:

mid = b[0]  + b[-1] // 2
print(mid)

This will print 4 or maybe 5 in my case its 5, which is the exact middle element of the list. Note that this method only works for lists with an even number of elements. If the list has an odd number of elements, then there is no exact middle element, and we have to use some other method.

Code: 


b = [1,2,3,4,5,6,7,8]
mid  = b[0]  +  b[-1]  / 2
print(mid)

# For more exact Answer

mid = b[0]  + b[-1] // 2
print(mid)

I hope you enjoyed this Python tip and learned something new. Stay tuned for more blog posts and happy coding!



Post a Comment

0Comments

Put Your Thought or Query Here

Post a Comment (0)