Python program to remove each y occurrence before x in List


When it is required to remove every ‘y’ occurrence before ‘x’ in a list, a list comprehension along with the ‘index’ method are used.

Example

Below is a demonstration of the same

my_list = [4, 45, 75, 46, 66, 77, 48, 99, 10, 40, 5, 8]

print("The list is :")
print(my_list)

a, b = 8, 4

index_a = my_list.index(a)

my_result = [ele for index, ele in enumerate(my_list) if ele != b or (ele == b and index > index_a) ]

print("The resultant list is ")
print(my_result)

Output

The list is :
[4, 45, 75, 46, 66, 77, 48, 99, 10, 40, 5, 8]
The resultant list is
[45, 75, 46, 66, 77, 48, 99, 10, 40, 5, 8]

Explanation

  • A list is defined and is displayed on the console.

  • Two variables are assigned integer values.

  • The index of one of the variables is obtained.

  • This is assigned to a variable.

  • A list comprehension is used to iterate through the list, using ‘enumerate’.

  • A condition is placed to check if the element is equal to (or not) the second variable.

  • The result of this operation is assigned to a variable.

  • This is displayed as the output on the console.

Updated on: 14-Sep-2021

77 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements