Sunday, 27 December 2020

Python: Check list emptiness using if condition

‘if list_name’

 

Syntax

if list_name:
    # List is not empty
else:
   # List is empty

 

Example

if list:
	for elem in list:
		print(elem)
	else:
		print("List is empty\n")

 

list_emptycheck.py

# Print elements of list
def print_elements(list):
   if list:
      for elem in list:
         print(elem)
   else:
      print("List is empty\n")

primes = []
print_elements(primes)

primes.append(2)
primes.append(3)
primes.append(5)
print_elements(primes)

Output

$ python3 list_empty_check.py 
List is empty

2
3
5


 

Previous                                                    Next                                                    Home

No comments:

Post a Comment