- Trending Categories
- Data Structure
- Operating System
- C Programming
- 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 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.
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)
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]
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.
- Program to remove last occurrence of a given target from a linked list in Python
- Program to count number of flipping required to make all x before y in Python
- Python program to find occurrence to each character in given string
- Python Program to Remove the nth Occurrence of the Given Word in a List where Words can Repeat
- Python program to test if all y occur after x in List
- C# program to remove the first occurrence of a node in a Linked List
- Program to remove string characters which have occurred before in Python
- Python program to remove elements at Indices in List
- Program to remove duplicate entries in a list in Python
- Why did changing list ‘y’ also change list ‘x’ in Python?
- Java program to check occurrence of each character in String
- Java program to check occurrence of each vowel in String
- Python program to remove Duplicates elements from a List?
- Python program to remove row with custom list element
- Python Program to Remove Palindromic Elements from a List