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:
- 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.
- my_list and string my_string: are respectively a list and a string both empty to make a test
- The if statement: is used to check if the length of each sequence is equal to 0.
- If the length is zero: we print a message indicating that the sequence is empty.
- If it's not equal to 0: we print a message indicating that the sequence is not empty.
Younes Derfoufi
my-courses.net
[…] Exercise 28 || Solution […]