How to Detect an Empty List in Python

The Python programming language has a special feature that lets you convert every piece of data into a Boolean value. There are two Boolean values: True and False. Python treats every non-zero number as True and all non-empty collections as True. Therefore, you can check to see if a list is empty by letting Python convert it to a Boolean type for you. In this way you can detect an empty list with one line of code.

Things You'll Need

  • PC with Python Programming Language
Show More

Instructions

    • 1

      Open the IDLE text editor that comes with the Python programming language. A blank source code file opens in the main editor window.

    • 2

      Declare an empty list by writing the following line of code:

      aList = []

    • 3

      Create an "if" statement and check to see if "aList" is empty. If "aList" is empty, it will evaluate as False when tested in an "if" statement. To test the list for emptiness, write the first line of the "if" statement like this:

      if aList:

    • 4

      Indent the next line by pressing the tab key. This line will execute if the list isn't empty. You can use this line to send a message to the console stating that the list is not empty. To send this message, write the following on this indented line:

      print("aList is not empty")

    • 5

      Create an "else" clause. The "else" clause executes only if the "if" statement evaluates as False. This occurs when the list is empty. You can write an "else" clause like this, on a new, un-indented line:

      else:

    • 6

      Print a message out to the console stating that the list is empty. Indent the next line using a tab and write the following code:

      print("aList is empty")

    • 7

      Execute the program by pressing the F5 key. The program output looks like this:

      aList is empty

Related Searches:

Resources

Comments

You May Also Like

Related Ads

Featured