Exercise 28

Write a Python program that tests whether a list is empty or not. Same question for a string of characters.

Solution

To tests whether a list or a string is empty or not we can use the len() function:

# Test if a list is empty or not
my_list = []
if len(my_list) == 0:
    print("The list is empty")
else:
    print("The list is not empty")

# Test if a string is empty or not
my_string = ""
if len(my_string) == 0:
    print("The string is empty")
else:
    print("The string is not empty")





Explanation:

  1. The len() function: returns the number of items in a sequence, such as a list or a string. If the length of the sequence is 0, then it is considered empty.
  2. my_list and string my_string: are respectively a list and a string both empty to make a test
  3. The if statement: is used to check if the length of each sequence is equal to 0.
  4. If the length is zero: we print a message indicating that the sequence is empty.
  5. If it's not equal to 0: we print a message indicating that the sequence is not empty.

 

Younes Derfoufi
my-courses.net

One thought on “Solution Exercise 28: test whether a Python list or string is empty”

Leave a Reply