Python – Check if a list is empty or not
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.
- 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
# Python code to check for empty list# Explicit waydef Enquiry[lis1]:if len[lis1] == 0:return 0else:return 1# Driver Codelis1 = []if Enquiry[lis1]:print ["The list is not empty"]else:print["Empty List"]Output:
Empty List - 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.
# Python code to check for empty list# IMPLICIT way or Pythonic waydef Enquiry[lis1]:if not lis1:return 1else:return 0# Driver Codelis1 = []if Enquiry[lis1]:print ["The list is Empty"]else:print ["The list is not empty"]Output:
The list is Empty
Numpythonic way
-
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.
# Numpythonic way with the previous method# Returns ValueErrorimport numpydef Enquiry[lis1]:return[numpy.array[lis1]]# Driver Codelis1 = [0, 1]if Enquiry[lis1]:print["Not Empty"]else:print["Empty"]Output:
NoneError:
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[] -
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.
# Numpythonic way with the previous method# Returns wrong resultimport numpydef Enquiry[lis1]:return[numpy.array[lis1]]# Driver Codelis1 = [0, ]if Enquiry[lis1]:print["Not Empty"]else:print["Empty"]Output:
Empty -
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:
# Numpythonic way to check emptiness# Use of sizeimport numpydef Enquiry[lis1]:return[numpy.array[lis1]]# Driver Codelis1 = []if Enquiry[lis1].size:print["Not Empty"]else:print["Empty"]Output:
Empty - This example shows the other case with a single 0 element, which failed in the previous cases.
# Numpythonic way to check emptiness# Use of sizeimport numpydef Enquiry[lis1]:return[numpy.array[lis1]]# Driver Codelis1 = [0, ]if Enquiry[lis1].size:print["Not Empty"]else:print["Empty"]Output:
Not Empty
Making the Numpythonic way work
For more reference visit PEP8 style guide.
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course
Linked Lists in Python: An Introduction
Table of Contents
Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Working With Linked Lists in Python
Linked lists are like a lesser-known cousin of lists. They’re not as popular or as cool, and you might not even remember them from your algorithms class. But in the right context, they can really shine.
In this article, you’ll learn:
- What linked lists are and when you should use them
- How to use collections.deque for all of your linked list needs
- How to implement your own linked lists
- What the other types of linked lists are and what they can be used for
If you’re looking to brush up on your coding skills for a job interview, or if you want to learn more about Python data structures besides the usual dictionaries and lists, then you’ve come to the right place!
You can follow along with the examples in this tutorial by downloading the source code available at the link below:
Get the Source Code: Click here to get the source code you’ll use to learn about linked lists in this tutorial.
With a root
The root acts as an element which is always present even if the list is empty.
The other use of having a root in list is that we can link the last element back to the root forming a cycle. According to this concept, next of any node is never NULL.
Pseudocode:
bool isEmpty[node *root]{ if [root->next == root] return true; else return false; }The implementation is given below:
#include using namespace std; class Node{ public: int data; Node *next; Node[]{ data=0; next=NULL; } }; class linked_list{ Node *root; public: linked_list[]{ root=NULL; } Node* getRoot[]{ return root; } void add_node[int n]{ Node *temp = new Node[]; temp->data = n; temp->next = NULL; if[root == NULL]{ root=temp; root->next=root; } else{ Node *last=root; while[last->next!=root]{ last=last->next; } temp->next=root; last->next=temp; } } void printList[]{ Node *temp=root; if[temp!=NULL]{ do{ coutdata==0] return true; return false; } }; int main[]{ linked_list l1; l1.add_node[5]; l1.add_node[10]; l1.add_node[15]; if[l1.isEmpty[]] cout