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
Python program to test if all y occur after x in List
When it is required to check if all 'y' occurs after 'x' in a list, the enumerate function along with a specific condition is used to compare indices.
Example
Below is a demonstration of the same ?
my_list = [11, 25, 13, 11, 64, 25, 8, 9]
print("The list is :")
print(my_list)
x, y = 13, 8
x_index = my_list.index(x)
my_result = True
for index, element in enumerate(my_list):
if element == y and index < x_index:
my_result = False
break
if(my_result == True):
print("All y elements occur after x elements")
else:
print("All y elements don't occur after x elements")
Output
The list is : [11, 25, 13, 11, 64, 25, 8, 9] All y elements occur after x elements
Method Using List Comprehension
We can also solve this using list comprehension to find indices of all occurrences ?
my_list = [11, 25, 13, 11, 64, 25, 8, 9]
print("The list is :")
print(my_list)
x, y = 13, 8
# Find first occurrence of x
x_index = my_list.index(x)
# Find all indices of y
y_indices = [i for i, val in enumerate(my_list) if val == y]
# Check if all y indices are greater than x index
all_after = all(i > x_index for i in y_indices)
if all_after:
print("All y elements occur after x elements")
else:
print("All y elements don't occur after x elements")
Output
The list is : [11, 25, 13, 11, 64, 25, 8, 9] All y elements occur after x elements
How It Works
A list is defined and displayed on the console.
Two integer variables
xandyare initialized.The index of the first occurrence of
xis found usingindex().Using
enumerate(), we iterate through the list to check each element.If any occurrence of
yhas an index less thanx_index, the result is set toFalse.Based on the final result, the appropriate message is displayed.
Conclusion
Use enumerate() to compare indices of elements in a list. This approach efficiently checks positional relationships between specific values in the list.
