Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python – K middle elements
When it is required to determine K middle elements from a list, the // operator and list slicing is used. This technique finds the center position of a list and extracts K consecutive elements around that center.
Syntax
# Calculate middle position middle = len(list) // 2 # Calculate start and end indices start_index = middle - (K // 2) end_index = middle + (K // 2) # Extract K middle elements result = list[start_index:end_index + 1]
Example
Here's how to extract 5 middle elements from a list ?
my_list = [34, 56, 12, 67, 88, 99, 0, 1, 21, 11]
print("The list is:")
print(my_list)
K = 5
print("The value of K is:")
print(K)
beg_indx = (len(my_list) // 2) - (K // 2)
end_indx = (len(my_list) // 2) + (K // 2)
my_result = my_list[beg_indx: end_indx + 1]
print("The result is:")
print(my_result)
The list is: [34, 56, 12, 67, 88, 99, 0, 1, 21, 11] The value of K is: 5 The result is: [67, 88, 99, 0, 1]
How It Works
First, we find the middle position using
len(my_list) // 2, which gives us index 5The beginning index is calculated as
middle - (K // 2) = 5 - 2 = 3The ending index is calculated as
middle + (K // 2) = 5 + 2 = 7We use
end_indx + 1in slicing because Python slicing excludes the end indexThe slice
[3:8]extracts elements at indices 3, 4, 5, 6, 7
Example with Different K Values
numbers = [10, 20, 30, 40, 50, 60, 70, 80, 90]
print("Original list:", numbers)
# Extract 3 middle elements
K = 3
middle = len(numbers) // 2
start = middle - (K // 2)
end = middle + (K // 2)
result = numbers[start:end + 1]
print(f"K={K} middle elements: {result}")
# Extract 7 middle elements
K = 7
start = middle - (K // 2)
end = middle + (K // 2)
result = numbers[start:end + 1]
print(f"K={K} middle elements: {result}")
Original list: [10, 20, 30, 40, 50, 60, 70, 80, 90] K=3 middle elements: [40, 50, 60] K=7 middle elements: [20, 30, 40, 50, 60, 70, 80]
Conclusion
To extract K middle elements, find the center position using integer division and calculate start/end indices by subtracting/adding K//2. This approach works efficiently for any list size and K value.
