- How to check if a list is empty in Python?
- How to check if a list is empty in Python?
- Table of Contents: Check if a list is empty in Python
- Why do you check if a list is empty in Python?
- Solution 1: Using PEP 8 recommended method:
- Solution 2: Using the bool() function
- Solution 3: Using len()
- Closing thoughts
- Check if Variable is Empty in Python
- Using is Operator
- Further reading:
- Using Comparison Operators
- Using len() Method
- Check if the variable is empty or not in Python
- Checking variable empty or not in Python
- LISTS – Check empty or not
- TUPLES – check empty or not
- STRING – Check empty or not
- DICTIONARY – Check empty or not
- NUMPY ARRAY – Check empty or not
- Python check if value is empty
- # Table of Contents
- # Check if user input is Empty in Python
- # Prevent the user from entering only spaces
- # Prevent empty user input
- # Prevent empty user input using a while loop
- # Setting default values on empty user Input in Python
- If a variable is empty Python | Example code
- How to check if a variable is empty in Python Example
- Check empty variable with if not statement
How to check if a list is empty in Python?
In this short tutorial, find how to check if a list is empty in Python. We also look at why you need to do this so that you understand the purpose better.
How to check if a list is empty in Python?
Empty lists are considered False in Python, hence the bool() function would return False if the list was passed as an argument. Other methods you can use to check if a list is empty are placing it inside an if statement, using the len() methods, or comparing it with an empty list.
Table of Contents: Check if a list is empty in Python
Why do you check if a list is empty in Python?
While dealing with lists, a major characteristic most developers make use of is its iterability. This means that you can iterate through the values in the list making it suitable for loops especially for. This also comes in handy while working with strings and numerical operations. And hence it is a good practice to check if a list is empty before proceeding.
This remains true for all iterables i.e dictionaries, tuples, etc.
With that out of the way, let us look at the various methods that can be used to check if a list is empty in Python.
Solution 1: Using PEP 8 recommended method:
Solution 1 & 2 make use of a method called **Truth Value Testing**. What this essentially means is that we check if the list is empty using its boolean value. This is possible because, in Python empty sequences, positional arguments containing 0, 0.0 or with length 0, are all considered to be false. You can read more about this here.
Because of this method, we can check if a list is empty in Python. And below is the most Pythonic way of checking the same.
l1 = ["Hire", "the", "top", "1%", "freelancers"] l2 = [] if l2: print("list is not empty") else: print("list is empty") #Output: "list is empty"
Since an empty list is False, the condition is false and hence we are able to identify an empty list. Feel free to change the condition with l1.
Another common method is with the Implication of a not.
sl1 = ["Hire", "the", "top", "1%", "freelancers"] l2 = [] if not l2: print("list is empty") else: print("list is not empty") # Output: "list is empty"
This is a similar approach however we use a not in the loop. It inverses the value and hence the condition becomes true. This method is used to increase readability as a developer could type the desired code under the else.
Solution 2: Using the bool() function
Similar to the first method, we check if a list is empty using the bool() function. The bool() function returns the boolean value of an object i.e true or false. The code is also very similar to the first method. Choosing between the two methods would boil down to a personal choice.
l1 = ["Hire", "the", "top", "1%", "freelancers"] l2 = [] if bool(l2): print("list is empty") else: print("list is not empty") # Output: "list is empty"
And since the value is false the print under the else is returned.
Solution 3: Using len()
In this solution, we use the len() to check if a list is empty, this function returns the length of the argument passed. And given the length of an empty list is 0 it can be used to check if a list is empty in Python.
Here again, there are two techniques that can be used. The first method is based on the Truth Value Testing, 0 is considered false.
l1 = ["Hire", "the", "top", "1%", "freelancers"] l2 = [] if len(l2): print("list is not empty") else: print("list is empty") # Output: "list is empty"
Here since the len() of l2 is 0 it is considered false and hence the condition returns the output under the else.
In the other methods, we use a condition to compare the length of the list with 0. Although this method is very similar to the first method this is mainly used to help improve readability.
l1 = ["Hire", "the", "top", "1%", "freelancers"] l2 = [] if len(l2) == 0: print("list is empty") else: print("list is not empty") # Output: "list is empty"
And since the condition is true, it returns the first value.
Closing thoughts
As you have seen there are multiple ways through which you can check if a list is empty in Python. And it is a good practice to use this condition before and then nest your if or for loops, this would help reduce unwanted errors.
And as to which solution would be the best choice, it again boils down to your knowledge of the language. If you are a beginner I would suggest you use the methods with the len( )== 0 as it is straightforward and readable. If you are proficient you can use solutions 1 or 2 but again I would recommend using the not l2 solution as it is more readable.
Check if Variable is Empty in Python
First, we declared a variable named name and initialized it with None. We use the None keyword in Python to define a null value or no value. Remember, None is not the same as an empty string, a zero or False value, but it is a built-in constant in Python, a data type of its own, which is NoneType .
Then, we used the if statement with the not keyword, which is used to determine if the given variable is empty or not. This keyword inverts the value of an object. As an empty object is treated as False , we can use the not keyword to invert the object’s value and check whether it is empty.
Using is Operator
Use the is operator to check if the specified variable is empty in Python.
This code is similar to the previous one, but we used the is operator to check if the specified variable is None . In Python, None represents the absence of the value, which means a variable is not assigned any value yet. So, if the variable is set to None , the name is None expression will return True and result in executing the if block; otherwise, the else block.
Further reading:
How to check if Variable is None in Python
How to check if Variable exists in Python
Using Comparison Operators
Use == operator to check if the variable is empty in Python.
Use != operator to check if the variable is empty in Python.
For this section, we used two comparison operators: == represents equal to and != denotes not equal to. These operators can be used if we know the variable’s data type.
For example, in the above two code examples, we knew that the variable would be empty if it equals None . The second code snippet using the != operator is similar to the previous example using the == operator, but we exchanged the print statements to get desired results.
Using len() Method
Use the len() method to check if the specified variable is empty in Python.
Check if the variable is empty or not in Python
In this tutorial, we will learn an easy yet important topic of how to check if the variable is empty or not in Python
The various sequences are:
Checking variable empty or not in Python
Now let’s first understand a little bit about these sequences.
LISTS – Check empty or not
- It is a data structure or data sequence in Python.
- Mutable in nature.
- Changeable in nature.
- Syntax to define a list is [ ].
TUPLES – check empty or not
- These are another type of data structure or data sequence.
- It’s immutable in nature.
- It’s irreversible which means no change can occur at any point.
- Syntax to define a list is ( ).
STRING – Check empty or not
- These are another type of data structure.
- It represents Unicode characters.
- [ ] can be used to access strings.
DICTIONARY – Check empty or not
- Dictionary is a random or unordered collection of data values.
- It has a key which is immutable in nature.
- Key should be unique also.
- Syntax to define a dictionary is .
NUMPY ARRAY – Check empty or not
- Numpy array is a grid of values.
- Values should be the same.
- Defined using numpy.array[].
Now let’s implement them using the python language.
NOTE: Any required explanation have been provided in code itself.
#Syntax to define a list l=[int(x) for x in input().split()] if len(l)==0: # len function to find the length of list print("The List is Empty") else: print("The list is not Empty")
-NO INPUT FROM USER SIDE- The List is Empty
#Syntax to define a String l=[x for x in input().split()] if len(l)==0: # len function to find the length of list print("The String is Empty") else: print("The String is not Empty")
-NO INPUT FROM USER SIDE- The String is Empty
#Syntax to define a list l=[int(x) for x in input().split()] a = tuple(l) #Convertig a list to tuple if len(l)==0: # len function to find the length of list print("The Tuple is Empty") else: print("The Tuple is not Empty")
-NO INPUT FROM USER SIDE- The Tuple is Empty.
#Syntax to define a list d= if(len(d)==0):#To find the length of dictionary print("Dictionary is Empty") else: print("Dictionary is not empty")
-NO INPUT FROM USER SIDE- Dictionary is Empty.
#Importing Numpy import numpy as np a = np.array([x for x in input().split()])#Syntax for defining Numpy Array if len(a)==0:#Len of Numpy Array print("Numpy array is empty") else: print("Numpy array is not empty")
Python check if value is empty
Last updated: Jan 28, 2023
Reading time · 4 min
# Table of Contents
# Check if user input is Empty in Python
Use an if statement to check if a user input is empty, e.g. if country == »: .
The input() function is guaranteed to return a string, so if it returns an empty string, the user didn’t enter a value.
Copied!country = input('Where are you from: ') if country == '': print('User input is empty') else: print('User input is NOT empty')
The first example uses an if statement to check if a user input is empty.
We directly check if the user didn’t enter anything.
# Prevent the user from entering only spaces
You can use the str.strip() method if you need to cover a scenario where the user enters only whitespace characters.
Copied!country = input('Where are you from: ') if country.strip() == '': print('User input is empty') else: print('User input is NOT empty')
The str.strip method returns a copy of the string with the leading and trailing whitespace removed.
Copied!print(repr(' '.strip())) # 👉️ '' print(repr(' bobbyhadz.com '.strip())) # 👉️ 'bobbyhadz.com'
# Prevent empty user input
The second example uses a while loop to keep prompting the user until they enter a non-empty value.
Copied!while True: country = input('Where are you from: ') if country.strip() != '': print(country) break
On each iteration, we check if the user entered at least one character.
If the condition is met, we use the break statement to exit the loop.
The break statement breaks out of the innermost enclosing for or while loop.
# Prevent empty user input using a while loop
Copied!country = '' while country.strip() == '': country = input('Where are you from: ')
We used a while loop to iterate until the country variable doesn’t store an empty string.
The input function takes an optional prompt argument and writes it to standard output without a trailing newline.
The function then reads the line from the input, converts it to a string and returns the result.
# Setting default values on empty user Input in Python
Use the or boolean operator to set a default value on empty user input. The boolean OR operator will return the default value if the input is empty.
Copied!default = 'English' user_input = input('Enter your preferred language: ') or default print(user_input) # ------------------------------------------- default = 100 user_input = int(input('Enter an integer: ') or default) print(user_input)
We used the boolean or operator to set a default value on empty user input.
The expression x or y returns the value to the left if it’s truthy, otherwise the value to the right is returned.
Copied!print('' or 'default value') # 👉️ default value print('hello' or 'default value') # 👉️ hello
If a variable is empty Python | Example code
You can Use bool() to check if a variable is empty in Python. Or you can also use if not statement to check it.
How to check if a variable is empty in Python Example
Simple python example code. Print True if the variable has a non-empty value, and False otherwise. Empty values include empty sequences, the integer 0, and the None value.
var1 = '' var2 = <> var3 = [1, 2, 3] var4 = None print(bool(var1)) print(bool(var2)) print(bool(var3)) print(bool(var4))
Check empty variable with if not statement
bool is used implicitly when evaluating an object in a condition like an if or while statement, conditional expression, or a boolean operator.
Just use not keyword:
var1 = '' if not var1: print("Variable is empty")
Output: Variable is empty
Do comment if you have any doubts and suggestions on this Python variable topic.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.