# Python – K middle elements

PythonServer Side ProgrammingProgramming

When it is required to determine K middle elements, the ‘//’ operator and list slicing is used.

Below is a demonstration of the same −

## Example

Live Demo

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)

## Output

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]

## Explanation

• A list is defined and is displayed on the console.

• A value for K is defined and is displayed on the console.

• The length of the list is obtained and the ‘//’ operator is used.

• The difference between above value and K//2 is assigned to a variable.

• The sum of these two values is also assigned to a different variable.

• A list slicing operation is done to access specific elements.

• This is assigned to a variable.

• This is displayed as the output on the console.

Updated on 04-Sep-2021 11:02:24