Python list empty element

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.

In this article, we will discuss different ways to check if a list is empty or not. We will also see how to check if a list of lists is empty or not using for loop, List comprehension, and all[] function.

Table of Contents

Check if a list is empty using ‘not’ operator in python

In python, a sequence object can be implicitly convertible to bool. If the sequence is empty, then it evaluates to False else it evaluates to True. So, we can apply an if statement to a sequence object to check if it is empty or not.

By applying if statement to the list object, we can check if it is empty pr not. For example,

# Create an empty list list_of_num = [] # Empty list object will evaluate to False if not list_of_num: print['List is empty'] else: print['List is not empty']

Output:

List is empty

How did it work?

When ‘if statement’ is applied to a list, it evaluates to False if list is empty, else it evaluates to True. If we apply the ‘not’ operator along with ‘if statement’ to the list object, it evaluates to True if the list is empty else returns False.

Check if list is empty using len[] function

Python provides a built-in function len[],

len[sequence]

It accepts a sequence like a list, tuple or set, etc, and returns the number of elements in that sequence i.e., size of the sequence.
We can check the list’s size by passing the list object to the len[] function. Once we have the list size, we can confirm if a list is empty by checking if its size is 0. For example,

# Create an empty list list_of_num = [] # Check if list's size is 0 if len[list_of_num] == 0: print['List is empty'] else: print['List is not empty']

Output:

List is empty

Python: Check if list is empty by comparing with empty list

In python, empty square brackets [] points to the empty list. So, we can check if our list object is empty or not by just comparing it with [] i.e.

# Create an empty list list_of_num = [] # Check if list object points to literal [] if list_of_num == []: print['List is empty'] else: print['List is not empty']

Output:

List is empty

This is not the quickest approach, because first empty list object will be created and then comparison will be done.

Check if list is empty using __len__[]

List class has a special overloaded method,

list.__len__[]

It returns the number of elements in the list. We can check the size of a list by calling __len__[] function on the list object. Once we have the list size, we can confirm if a list is empty by checking if its size is 0. For example,

# Create an empty list list_of_num = [] # Check if list's size is 0 if list_of_num.__len__[] == 0: print['List is empty'] else: print['List is not empty']

Output:

List is empty

Check if a list is empty using numpy

Convert a Python list to a numpy array and then check the numpy array size using attribute size. If the size of the numpy array is zeo then it means the list is empty. For example,

import numpy as np # Create an empty list list_of_num = [] arr = np.array[list_of_num] if arr.size == 0: print['List is empty'] else: print['List is not empty']

Output:

List is empty

Check if a list of lists is empty

There might be scenarios when we have a list of lists, and we want to find out if all sub-lists are empty. There are different ways to do that. Let’s discuss them one by one.

Check if a list of lists is empty using for loop

We have created a function that accepts a list of lists and checks if all sub-lists in the given list are empty or not. Let’s use this function to check if all lists in a list are empty or not.

def check_if_empty[list_of_lists]: for elem in list_of_lists: if elem: return False return True # List of list list_of_lists = [ [], [], [], []] if check_if_empty[list_of_lists]: print['List of Lists is empty'] else: print['List of Lists is not empty']

Output:

List of Lists is empty

This function check_if_empty[] accepts a list of lists, then iterates over all the sublists in the main list using for loop, and for each sub-list, it checks if it is empty or not using ‘if condition’ & ‘not operator’. If any of the sub-lists is non-empty, it returns False, whereas if all sub-lists are empty, it returns True.

Check if a list of lists is empty using List comprehension

Unlike the previous solution, here we will check if all sublists in a given list are empty or not in a single like using List Comprehension and all[] function.

def check_if_empty_2[list_of_lists]: return all[[not elem for elem in list_of_lists ]] # List of list list_of_lists = [ [], [], [], []] if check_if_empty_2[list_of_lists]: print['List of Lists is empty'] else: print['List of Lists is not empty']

Output:

List of Lists is empty

List comprehension returned a list of bools, where each entry in this boolean list represents the sublist from the main list. If a sub-list was empty, then the corresponding entry in this bool list will be True else False.
Then we passed this bool list to the all[] function to check if all elements in this bool list are True or not. If all the bool list elements are True, then it means all sub-lists in the main list are empty.

Summary

We discussed different ways to check if a list is empty or not. Then we also looked into the techniques to check if a list contains all empty lists or not.

Video liên quan

Chủ Đề