
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Python – K middle elements
When it is required to determine K middle elements, the ‘//’ operator and list slicing is used.
Below is a demonstration of the same −
Example
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.
- Related Articles
- Python – Reform K digit elements
- Maximum possible middle element of the array after deleting exactly k elements in C++
- Top K Frequent Elements in Python
- Middle of three elements - JavaScript
- Python – Next N elements from K value
- Python – Random insertion of elements K times
- Program to find k where k elements have value at least k in Python
- Delete elements with frequency atmost K in Python
- Extract tuples having K digit elements in Python
- Python – Remove Elements in K distance with N
- Python – Elements with factors count less than K
- Python program to find Non-K distant elements
- Maximum and Minimum K elements in Tuple using Python
- Python program to replace first ‘K’ elements by ‘N’
- Python – Filter rows with Elements as Multiple of K

Advertisements