13

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"
1
  • No need to use len(), an empty list is falsy. Commented Mar 20, 2013 at 12:36

2 Answers 2

23

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.

Sign up to request clarification or add additional context in comments.

3 Comments

This answers OP question but it general this won't work when iterated object is e.g. a generator. Then the options are to add flag to loop or check for NameError: name 'x' is not defined but the latter is more error prone. I currently have a use case where such empty block would solve my issue and make code more idiomatic.
@WloHu: for generators, there is no way to know, up-front, if they are going to be empty. Your options are to peek (fetch one element, if that fails, treat it as empty, if it succeeds, perhaps use itertools.chain([peeked_element], generator) to loop the element back in), or detect that case by setting the for loop target name (e.g. x in the loop in my answer) to a sentinel value like None before the loop then test if the variable is still referencing the sentinel after the loop. Only if the generator was empty and never produces the sentinel object would that condition still be true.
@WloHu: for this question, where the object is clearly a list (my_list as a variable name), there is no need to make things that complicated, however.
3

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"

1 Comment

let me stress that this will work fine even when my_list is an iterator

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.