Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"
like image 732
Crazyshezy Avatar asked Mar 20 '13 12:03

Crazyshezy


2 Answers

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.

like image 166
Martijn Pieters Avatar answered Oct 01 '22 22:10

Martijn Pieters


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"
like image 32
am70 Avatar answered Oct 01 '22 23:10

am70