Why is my list empty python

In this article, we will learn How to check if given list is Empty or not. There are various ways in which a list can be checked in Python, but all are not appropriate or in the terms of Python, “pythonic”, to implement.

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

    def Enquiry[lis1]:

        if len[lis1] == 0:

            return 0

        else:

            return 1

    lis1 = []

    if Enquiry[lis1]:

        print ["The list is not empty"]

    else:

        print["Empty List"]

    Output:

    Empty List
  2. Now let’s see a more pythonic way to check for an empty list. This method of check is an implicit way of checking and more preferable than the previous one.

    def Enquiry[lis1]:

        if not lis1:

            return 1

        else:

            return 0

    lis1 = []

    if Enquiry[lis1]:

        print ["The list is Empty"]

    else:

        print ["The list is not empty"]

    Output:

    The list is Empty

Numpythonic way

  1. The previous methods that we used in normal Python don’t work for the Numpythonic way. Other methods that work fine for lists or other standard containers fail for numpy arrays. This way fails with numpy arrays because numpy tries to cast the array to an array of bools and if this tries to evaluate all of those bools at once for some kind of aggregate truth value, it fails so we get a ValueError.

    import numpy

    def Enquiry[lis1]:

        return[numpy.array[lis1]]

    lis1 = [0, 1]

    if Enquiry[lis1]:

        print["Not Empty"]

    else:

        print["Empty"]

    Output:

    None

    Error:

    Traceback [most recent call last]: File "/home/2d237324bb5211d7216c521441a750e9.py", line 7, in if Enquiry[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 show Empty. If the list contains one 0, then the if statement will incorrectly result.

    import numpy

    def Enquiry[lis1]:

        return[numpy.array[lis1]]

    lis1 = [0, ]

    if Enquiry[lis1]:

        print["Not Empty"]

    else:

        print["Empty"]

    Output:

    Empty

    Making the Numpythonic way work

    1. If we have a numpy array then correct method in all cases, is to use if .size. This size checks the size of the arrays and return True or False accordingly.
      Example:

      import numpy

      def Enquiry[lis1]:

          return[numpy.array[lis1]]

      lis1 = []

      if Enquiry[lis1].size:

          print["Not Empty"]

      else:

          print["Empty"]

      Output:

      Empty
    2. This example shows the other case with a single 0 element, which failed in the previous cases.

      import numpy

      def Enquiry[lis1]:

          return[numpy.array[lis1]]

      lis1 = [0, ]

      if Enquiry[lis1].size:

          print["Not Empty"]

      else:

          print["Empty"]

      Output:

      Not Empty

    For more reference visit PEP8 style guide.

Check whether a list is empty or not in different ways.

There are multiple ways to check whether a list is empty or not in Python. Let’s see them one by one.

Length

We can check whether a list is empty or not using the length of the list. It’s a straightforward solution and most people get it as a first approach. Let’s see the steps to check the list emptiness.

  • Write a function called is_list_empty that takes a list as an argument.
  • Check the length of the list.
    • If the length is 0, then return True else return False.

That’s it. We are done with the steps involved in the program.

Let’s code.

# function to check whether the list is empty or not def is_list_empty[list]: # checking the length if len[list] == 0: # returning true as length is 0 return True # returning false as length is greater than 0 return False

Let’s check our function with the following code.

list_one = [1, 2, 3] list_two = [] print[is_list_empty[list_one]] print[is_list_empty[list_two]]

You will get the following result if you execute the above code.

False True

Bool

The boolean value of an empty list is always False. Here, we will take the advantage of the bool method. We are going to use the bool conversion method to check whether the list is empty or not. Let’s see the steps involved in it.

  • Write a function called is_list_empty that takes a list as an argument.
  • Convert the list to boolean using bool method.
  • Inver the result and return it.

Yeah! that’s it. We are done with the steps. Let’s see the code.

# function to check whether the list is empty or not def is_list_empty[list]: # returning boolean value of current list # empty list bool value is False # non-empty list boolea value is True return not bool[list]

Let’s test our function with the following code.

list_one = [1, 2, 3] list_two = [] print[is_list_empty[list_one]] print[is_list_empty[list_two]]

You will get the same output as we have seen in the previous example. Execute and test it.

Equality Operator

There is another simple way to check the list is empty or not. We can directly compare the list with empty list [[]]. Python returns True if the given list matches with the empty list.

Let’s see the steps to check whether the list is empty or not with the equality operator.

  • Write a function called is_list_empty that takes a list as an argument.
  • Compare the given list with [] and return the list.

One simple step gives you a lot in Python. Let’s see the code.

# function to check whether the list is empty or not def is_list_empty[list]: # comparing the list with [] # and returning the result return list == []

Now, you can check the function with code snipped that we have used in this tutorial. You will get the same output as before.

Conclusion

That’s more than enough for the developers to check the emptiness of a list.

There might be other ways to check whether the list is empty or not. We have seen some of them. Choose the method that best suits you.

Interested in mastering Python? Check out this course.

Happy Coding 🙂

Lists are one of the four most commonly used data structures provided by Python. Its functionality, extensibility, and ease of use make it useful for implementing various types of functionalities.

Python lists have a few interesting characteristics:

  1. Mutability - meaning it can change, which means it allows us to easily add and delete entries from it. This is the main difference between Python lists and tuples
  2. Iterability - which means we can iterate through it [go through all elements in the list in-order]

The main attribute that will be focusing on is Iterability. An important part when dealing with an iterable object, in this case a list, is checking if there's anything to iterate through. If not handled properly, this can lead to a lot of unwanted errors.

Python provides various ways to check if our list is empty or not, some implicit and some explicit, and in this article, we'll go over how to check if a Python list is empty.

Using len[] Function

One of the techniques is to use the len[] function to check if our list is empty or not:

py_list = [] """ Here len[] returns 0, which is implicitly converted to false """ if len[py_list]: print['The list is not empty'] else: print['T list is empty']

Output

List is empty

When len[py_list] executes it produces zero, which is then implicitly cast to the boolean value of False. Thus in case of an empty list the program will be redirected to the else block.

Although this method looks simple, it's not that intuitive for beginners.

Using len[] With Comparison Operator

This technique is similar to the one above but it is more explicit and easy to understand. That's why those who are new to python or coding itself usually consider it more intuitive:

if len[py_list] == 0: print['List is empty'] else: print['List not empty']

In the code above, len[py_list] == 0 will be true if the list is empty and will will be redirected to the else block. This also allows you to set other values as well, rather than relying on 0 being converted as False. All other positive values are converted to True.

Comparison With Empty List

This method is also very simple and works well for beginners as it involves comparing with an empty list:

if py_list == []: print['List is empty'] else: print['List is not empty']

Here again, we are using the comparison operation to compare one list with another - am empty one, and if both are empty the if block will execute.

Pep-8 Recommended Style

if py_list: print['List is not empty'] if not py_list: print['List empty']

For this, let's take a look at Truth Value Testing. The official docs state that:

Here are most of the built-in objects considered false:

  • constants defined to be false: None and False.
  • zero of any numeric type: 0, 0.0, 0j, Decimal[0], Fraction[0, 1]
  • empty sequences and collections: '', [], [], {}, set[], range[0]

As an empty list is in fact just a empty collection, it will be converted to a boolean value of False. Therefore, if py_list is empty, it will converted to False.

The second statement is pretty similar, except not will invert the a false condition to a true one. This approach is very similar to the if[len[list]] approach.

This is the preferred approach as it's the cleanest and shortest solution there is.

Using bool[] Function

We can also use the bool[] function to verify a list is empty:

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

if bool[py_list]: print['List is not empty'] else: print['List is empty']

This is basically a manually implemented truth value test. So if the list is not empty the function will return True and if block will be executed.

This approach is less common as we can achieve the desired results even without using bool[], but it's not a bad thing to know how Python works under the hood.

Conclusion

This article was all about ways to check if our python list is empty or not. We started by exploring different techniques and finally looking into some parameters that we can use to make our judgment regarding which technique may work for us.

I can't say that this is the end as new Python updates may give rise to new and more improved coding styles. So it's better to keep exploring and keep learning.

Video liên quan

Chủ Đề