How to Remove a List in Python Iteration

Removing elements from your Python list is helpful when you need to shorten the list according to a specific condition. For example, you may start with a list containing all the numbers from one to 10 and you want to remove all the odd numbers. Create a list of values, iterate through the list with a "for" loop, check a condition and remove matching elements with the "del" statement.

Instructions

    • 1

      Open the Python source file in an editor, such as Microsoft Windows Notepad.

    • 2

      Declare a list and initialize it with values by adding the following code at the top of the file:

      mylist = [3, 5, 7, 9]

    • 3

      Iterate through the list and remove elements that satisfy a specific condition by adding the following code:

      for i in xrange(len(mylist) - 1, -1, -1):
      if mylist[i] > 6:
      del mylist[i]

      Python requires proper indenting, so press the "Tab" key once before the second line and twice before the third line of code.

      The "xrange" function creates an "xrange object", which contains the values from the list. The "for" loop starts at the end of the list and iterates backward until it reaches the beginning. The code removes any elements from the list that have a value greater than six.

    • 4

      Display the new contents of the list by adding the following code:

      print mylist

      The code will output the list "[3, 5]."

    • 5

      Save the file with a ".py" extension. Execute the code to remove items from your Python list.

Related Searches:

References

Comments

Related Ads

Featured