7.5 C
New York
Wednesday, March 22, 2023

Check if a List, Array, Set, Tuple, String or Dictionary is Empty in Python?

The best way to check if any List, Set, Tuple, String or Dictionary is empty is by if statement.

Check if List or Array is Empty

llist = []
if not llist:
	 print("List is empty")
else:
 print("List is not empty")

OutPut
List is empty

Check if Set is Empty

sset = set()
if not sset:
	 print("Set is empty")
else:
 print("Set is not empty")

OutPut
Set is empty

Check if Dictionary is Empty

ddir = {}
if not ddir:
 print("Dictionary is empty")
else:
 print("Dictionary is not empty")

OutPut
Dictionary is empty

Check if Tuple is Empty

ttuple = ()
if not ttuple:
 print("Tuple is empty")
else:
 print("Tuple is not empty")

OutPut
Tuple is empty

Check if String is Empty

sstring = ''
if not sstring:
 print("String is empty")
else:
 print("String is not empty")

OutPut
String is empty

Check if a List is Empty by using len()

llist = []
if len(llist) == 0:
 print("List is empty")
else:
 print("List is not empty")

OutPut
List is empty

But it is not advisable to use len() function to because it is very pythonic.

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles