- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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.
Advertisements