'for/empty loop condition in python
In Django templates, For loop has a empty conditions which gets set only when the object you are looping over is empty.
e.g:
{% for x in my_list %}
#do something
{% empty %}
<p> my_list is empty </p>
{% endfor %}
here if my_list is empty then it will just print my_list is empty
Is there something equivalent in python?
I am using if-else conditions but that's ugly looking. I am trying to find a solution that does not involve using a if-else condition
my current code:
if len(my_list):
for x in my_list:
doSomething()
else:
print "my_list is empty"
Solution 1:[1]
You'll have to stick with the if statement, but it can be simplified:
for x in my_list:
doSomething()
if not my_list:
print "my_list is empty"
since my_list is empty, the for loop never executes the loop portion, and an empty list is False in a boolean context.
Solution 2:[2]
if you are sure that the iterator is not returning a specific value, say None or False, then you can
x = False
for x in my_list:
doSomething(x)
if x is False:
print "my_list is empty"
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Martijn Pieters |
| Solution 2 | am70 |
