Change language

Python | Check if the list is empty or not

| | |

There are various ways to validate a list in Python, but none of them are appropriate or appropriate for Python, "pythonic", to implement.

  1. Let’s see how we can check if a list is empty or not , in a less pythonic way. We must avoid this way of explicitly checking a sequence or list
    Example:

    # Python code to check for empty list
    # Explicit way

    def Inquiry (lis1):

    if len (lis1) = = 0 :

    return 0

    else :

    return 1

     
    Driver code

    lis1 = []

    if Inquiry (lis1):

    print ( "The list is not empty" )

    else :

    print ( "Empty List" )

    Exit:

     Empty List 
  2. Now let’s look at a more pythonic way to check for an empty list. This verification method is a implicit verification method and is preferred over the previous one.
    Example:

    # Python code to check for empty list
    # ILLEGAL way or Pythonic way

    def Inquiry (lis1):

      if not lis1:

      return 1

    else :

    return 0

     
    Driver code

    lis1 = []

    if Inquiry (lis1):

    print ( "The list is Empty " )

    else :

    print ( "The list is not empty" )

    Output:

     The list is Empty 

Numpythonic path

  1. The previous methods we used in regular Python don’t work digitally . Other methods that work fine for lists or other standard containers, not work for empty arrays . This way fails with numpy arrays because numpy tries to cast the array to an array of bools, and if it tries to evaluate all of those bools at the same time for some cumulative truth value, it fails, so we get a ValueError. 
    Example 1:

    # Numpythonic method with the previous method
    # Returns ValueError

    import numpy

    def Inquiry (lis1):

    return (numpy.array (lis1))

     
    Driver code

    lis1 = [ 0 , 1 ]

    if Inquiry (lis1):

    pri nt ( "Not Empty" )

    else :

    print ( "Empty" )

    Output:

     None 

    Error:

     Traceback (most recent call last): File "/home/2d237324bb5211d7216c521441a750e9.py", line 7, in if Inquiry (lis1): ValueError: The truth value of an array with more than one element is ambiguous. Use a.any () or a.all () 
  2. In the next example, we will see that even if the list is not empty, the output will be empty. If the list contains one 0, then the if statement will be incorrectly received. 
    Example 2:

    Output:

     Empty 

    Make Numpythonic work

    1. If we have an empty array, then the correct method in all cases is — use if .size . This size checks the size of the arrays and returns True or False, respectively. 
      Example:

    # Numpythonic method with the previous method
    # Returns an incorrect result

    import numpy

    def Inquiry (lis1):

    return (numpy.array (lis1))

     
    Driver code

    lis1 = [ 0 ,]

    if Inquiry (lis1):

    print ( "Not Empty" )

    else :

      print ( "Empty" )

    # Numpythonic way to check for emptiness
    # Using size

    import numpy

    def Inquiry (lis1):

    return (numpy.array (lis1))

     
    Driver code

    lis1 = []

    if Inquiry (lis1) .size:

    print ( " Not Empty " )

      else :

    print ( "Empty" )

    Exit:

     Empty 
  3. Example 2:
    This example shows another case with one element 0, which failed in the previous cases.

    # Numpythonic way to check for emptiness
    # Using size

    import numpy

    def Inquiry (lis1):

    return (numpy.array (lis1))

      Driver code

    lis1 = [ 0 ,]

    if Inquiry (lis1) .size:

    print ( "Not Empty" )

    else :

    print ( " Empty " )

    Output:

     Not Empty 

For more information visit PEP8 Style Guide .

Shop

Learn programming in R: courses

$

Best Python online courses for 2022

$

Best laptop for Fortnite

$

Best laptop for Excel

$

Best laptop for Solidworks

$

Best laptop for Roblox

$

Best computer for crypto mining

$

Best laptop for Sims 4

$

Latest questions

NUMPYNUMPY

Common xlabel/ylabel for matplotlib subplots

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

12 answers

NUMPYNUMPY

Flake8: Ignore specific warning for entire file

12 answers

NUMPYNUMPY

glob exclude pattern

12 answers

NUMPYNUMPY

How to avoid HTTP error 429 (Too Many Requests) python

12 answers

NUMPYNUMPY

Python CSV error: line contains NULL byte

12 answers

NUMPYNUMPY

csv.Error: iterator should return strings, not bytes

12 answers

News


Wiki

Python | How to copy data from one Excel sheet to another

Common xlabel/ylabel for matplotlib subplots

Check if one list is a subset of another in Python

sin

How to specify multiple return types using type-hints

exp

Printing words vertically in Python

exp

Python Extract words from a given string

Cyclic redundancy check in Python

Finding mean, median, mode in Python without libraries

cos

Python add suffix / add prefix to strings in a list

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

Python - Move item to the end of the list

Python - Print list vertically