
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Extract Element from a List Succeeded by K in Python
When it is required to extract element from a list succeeded by ‘K’, a simple iteration and the ‘append’ method is used.
Example
Below is a demonstration of the same
my_list = [45, 65, 32, 78, 99, 10, 21, 2] print("The list is : ") print(my_list) K = 99 print("The value of K is ") print(K) my_result = [] for elem in range(len(my_list) - 1): if my_list[elem + 1] == K: my_result.append(my_list[elem]) print("The result is : " ) print(my_result)
Output
The list is : [45, 65, 32, 78, 99, 10, 21, 2] The value of K is 99 The result is : [78]
Explanation
A list is defined and is displayed on the console.
The value for ‘K’ is defined and is displayed on the console.
An empty list is defined.
The list is iterated over and every element is checked to be equivalent to ‘K’.
If so, it is appended to the empty list using the ‘append’ method.
This list is displayed as the output on the console.
Advertisements