How to check if the container is empty by python
This article mainly introduces python how to check whether the container is empty, has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, the following let the editor take you to understand it.
Check whether the container is empty
Containers are those container data types that can store other data. Some of the frequently used built-in containers are tuples, lists, dictionaries, and collections. When dealing with these containers, we often need to check to see if they contain any elements before performing other operations. Indeed, we can check the length of these containers, which corresponds to the number of items that have been stored. When the length is 00:00, the container is empty. A simple example is shown below.
If len (some_list) > 0: # do something here when the list is not empty else: # do something else when the list is empty
However, this is not the best way to Pythonic. Instead, we can simply examine the container itself, which will be evaluated when the container True contains elements. Although the following code shows you the main container data types, this usage can also be applied to strings (that is, any non-empty string is True).
Def check_container_empty (container):... If container:... Print (f "{container} has elements."). Else:... Print (f "{container} doesn't have elements."). Check_container_empty ([1,2,3]). Check_container_empty (set ())... Check_container_empty ({"zero": 0, "one": 1}). Check_container_empty (tuple ())... [1,2,3] has elements. Set () doesn't have elements. {'zero': 0,' one': 1} has elements. () doesn't have elements. Thank you for reading this article carefully. I hope the article "how to check whether the container is empty" shared by the editor will be helpful to everyone. At the same time, I also hope that you will support and follow the industry information channel. More related knowledge is waiting for you to learn!