OneBite.Dev - Coding blog in a bite size

remove a specific element from an array in python

Code snippet on how to remove a specific element from an array in python

  myArray = [1, 2, 3, 4, 5, 6] 
  removingElement = 4
  
  myArray[:] = [x for x in myArray if x != removingElement] 

This code uses a list comprehension to build a new list out of the existing one. It begins with the line myArray[:] =, which operates on the existing list, assigning the results of the code on the right-hand side to the list on the left. On the right side, the code starts off with a list comprehension. This is a special way of writing a loop that is expression-oriented instead of imperative. It starts with the expression x for x in myArray, which will loop through each item in myArray, and assign them each to a new variable called x. This expression is followed by a conditional if x != removingElement , which will make the program skip any items in the list that are equal to removingElement. The end result is that the updated list will be assigned back to the original list.

python