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
Selected Reading
Python – Extract element from a list succeeded by K
When it is required to extract elements from a list that are succeeded by K (elements that come before K), we can use simple iteration with the append method or list comprehension.
Method 1: Using Loop
Iterate through the list and check if the next element equals K ?
numbers = [45, 65, 32, 78, 99, 10, 21, 2]
print("The list is:")
print(numbers)
K = 99
print("The value of K is:")
print(K)
result = []
for i in range(len(numbers) - 1):
if numbers[i + 1] == K:
result.append(numbers[i])
print("Elements succeeded by K:")
print(result)
The list is: [45, 65, 32, 78, 99, 10, 21, 2] The value of K is: 99 Elements succeeded by K: [78]
Method 2: Using List Comprehension
A more concise approach using list comprehension ?
numbers = [45, 65, 32, 78, 99, 10, 21, 2, 99, 50]
K = 99
result = [numbers[i] for i in range(len(numbers) - 1) if numbers[i + 1] == K]
print(f"Elements succeeded by {K}: {result}")
Elements succeeded by 99: [78, 2]
Method 3: Using zip()
Using zip() to pair adjacent elements ?
numbers = [1, 5, 3, 5, 7, 5, 9]
K = 5
result = [current for current, next_elem in zip(numbers, numbers[1:]) if next_elem == K]
print(f"Elements succeeded by {K}: {result}")
Elements succeeded by 5: [1, 3, 7]
Comparison
| Method | Readability | Best For |
|---|---|---|
| Loop | High | Beginners, clear logic |
| List Comprehension | Medium | Concise one-liner |
| zip() | Medium | Functional programming style |
Conclusion
Use the loop method for clarity and readability. List comprehension provides a concise solution, while zip() offers a functional approach for pairing adjacent elements.
Advertisements
