<p>For example, if passed the following:</p>

<pre><code>a = []
</code></pre>

<p>How do I check to see if <code>a</code> is empty?</p>

[{'answer_id': 53522, 'author': 'Patrick', 'author_id': 429, 'author_profile': 'https://Stackoverflow.com/users/429', 'pm_score': 14, 'selected': True, 'text': '<pre><code>if not a:\n    print(&quot;List is empty&quot;)\n</code></pre>\n<p>Using the <a href="https://docs.python.org/library/stdtypes.html#truth-value-testing" rel="noreferrer">implicit booleanness</a> of the empty <code>list</code> is quite Pythonic.</p>\n'}, {'answer_id': 53525, 'author': 'Peter Hoffmann', 'author_id': 720, 'author_profile': 'https://Stackoverflow.com/users/720', 'pm_score': 7, 'selected': False, 'text': '<p>An empty list is itself considered false in true value testing (see <a href="https://docs.python.org/2/library/stdtypes.html#truth-value-testing" rel="nofollow noreferrer">python documentation</a>):</p>\n<pre><code>a = []\nif a:\n     print(&quot;not empty&quot;)\n</code></pre>\n<p>To <a href="https://stackoverflow.com/questions/53513/how-do-i-check-if-a-list-is-empty/53530#53530">Daren Thomas\'s answer</a>:</p>\n<blockquote>\n<p>EDIT: Another point against testing\nthe empty list as False: What about\npolymorphism? You shouldn\'t depend on\na list being a list. It should just\nquack like a duck - how are you going\nto get your duckCollection to quack\n\'\'False\'\' when it has no elements?</p>\n</blockquote>\n<p>Your duckCollection should implement <code>__nonzero__</code> or <code>__len__</code> so the if a: will work without problems.</p>\n'}, {'answer_id': 53533, 'author': 'verix', 'author_id': 5342, 'author_profile': 'https://Stackoverflow.com/users/5342', 'pm_score': 5, 'selected': False, 'text': '<p>I prefer the following:</p>\n\n<pre><code>if a == []:\n   print "The list is empty."\n</code></pre>\n'}, {'answer_id': 53752, 'author': 'Harley Holcombe', 'author_id': 1057, 'author_profile': 'https://Stackoverflow.com/users/1057', 'pm_score': 10, 'selected': False, 'text': '<p>The Pythonic way to do it is from the <a href="https://www.python.org/dev/peps/pep-0008" rel="noreferrer">PEP 8 style guide</a>.</p>\n<blockquote>\n<p>For sequences, (strings, lists, tuples), use the fact that empty sequences are false:</p>\n<pre class="lang-python prettyprint-override"><code># Correct:\nif not seq:\nif seq:\n\n# Wrong:\nif len(seq):\nif not len(seq):\n</code></pre>\n</blockquote>\n'}, {'answer_id': 61918, 'author': 'George V. Reilly', 'author_id': 6364, 'author_profile': 'https://Stackoverflow.com/users/6364', 'pm_score': 6, 'selected': False, 'text': '<p><a href="http://books.google.com/books?id=vpTAq4dnmuAC&amp;pg=RA1-PA479&amp;lpg=RA1-PA479&amp;dq=Python+len+big+O&amp;source=web&amp;ots=AOM6A1K9Fy&amp;sig=iQo8mV6Xf9KdzuNSa-Jkr8wDEuw&amp;hl=en&amp;sa=X&amp;oi=book_result&amp;resnum=4&amp;ct=result" rel="noreferrer"><code>len()</code> is an O(1) operation</a> for Python lists, strings, dicts, and sets. Python internally keeps track of the number of elements in these containers.</p>\n\n<p>JavaScript <a href="http://www.isolani.co.uk/blog/javascript/TruthyFalsyAndTypeCasting" rel="noreferrer">has a similar notion of truthy/falsy</a>.</p>\n'}, {'answer_id': 7302987, 'author': 'Jabba', 'author_id': 232485, 'author_profile': 'https://Stackoverflow.com/users/232485', 'pm_score': 10, 'selected': False, 'text': "<p>I prefer it explicitly:</p>\n\n<pre><code>if len(li) == 0:\n    print('the list is empty')\n</code></pre>\n\n<p>This way it's 100% clear that <code>li</code> is a sequence (list) and we want to test its size. My problem with <code>if not li: ...</code> is that it gives the false impression that <code>li</code> is a boolean variable.</p>\n"}, {'answer_id': 9381545, 'author': 'Mike', 'author_id': 1194883, 'author_profile': 'https://Stackoverflow.com/users/1194883', 'pm_score': 9, 'selected': False, 'text': '<p><sub>This is the first google hit for &quot;python test empty array&quot; and similar queries, and other people are generalizing the question beyond just lists, so here\'s a caveat for a different type of sequence that a lot of people use.</sub></p>\n<h1>Other methods don\'t work for NumPy arrays</h1>\n<p>You need to be careful with NumPy arrays, because other methods that work fine for <code>list</code>s or other standard containers fail for NumPy arrays.  I explain why below, but in short, the <a href="http://www.scipy.org/scipylib/faq.html#what-is-the-preferred-way-to-check-for-an-empty-zero-element-array" rel="nofollow noreferrer">preferred method</a> is to use <code>size</code>.</p>\n<h2>The &quot;pythonic&quot; way doesn\'t work: Part 1</h2>\n<p>The &quot;pythonic&quot; way fails with NumPy arrays because NumPy tries to cast the array to an array of <code>bool</code>s, and <code>if x</code> tries to evaluate all of those <code>bool</code>s at once for some kind of aggregate truth value.  But this doesn\'t make any sense, so you get a <code>ValueError</code>:</p>\n<pre><code>&gt;&gt;&gt; x = numpy.array([0,1])\n&gt;&gt;&gt; if x: print(&quot;x&quot;)\nValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()\n</code></pre>\n<h2>The &quot;pythonic&quot; way doesn\'t work: Part 2</h2>\n<p>But at least the case above tells you that it failed.  If you happen to have a NumPy array with exactly one element, the <code>if</code> statement will &quot;work&quot;, in the sense that you don\'t get an error.  However, if that one element happens to be <code>0</code> (or <code>0.0</code>, or <code>False</code>, ...), the <code>if</code> statement will incorrectly result in <code>False</code>:</p>\n<pre><code>&gt;&gt;&gt; x = numpy.array([0,])\n&gt;&gt;&gt; if x: print(&quot;x&quot;)\n... else: print(&quot;No x&quot;)\nNo x\n</code></pre>\n<p>But clearly <code>x</code> exists and is not empty!  This result is not what you wanted.</p>\n<h2>Using <code>len</code> can give unexpected results</h2>\n<p>For example,</p>\n<pre><code>len( numpy.zeros((1,0)) )\n</code></pre>\n<p>returns 1, even though the array has zero elements.</p>\n<h2>The numpythonic way</h2>\n<p>As explained in the <a href="http://www.scipy.org/scipylib/faq.html#what-is-the-preferred-way-to-check-for-an-empty-zero-element-array" rel="nofollow noreferrer">SciPy FAQ</a>, the correct method in all cases where you know you have a NumPy array is to use <code>if x.size</code>:</p>\n<pre><code>&gt;&gt;&gt; x = numpy.array([0,1])\n&gt;&gt;&gt; if x.size: print(&quot;x&quot;)\nx\n\n&gt;&gt;&gt; x = numpy.array([0,])\n&gt;&gt;&gt; if x.size: print(&quot;x&quot;)\n... else: print(&quot;No x&quot;)\nx\n\n&gt;&gt;&gt; x = numpy.zeros((1,0))\n&gt;&gt;&gt; if x.size: print(&quot;x&quot;)\n... else: print(&quot;No x&quot;)\nNo x\n</code></pre>\n<p>If you\'re not sure whether it might be a <code>list</code>, a NumPy array, or something else, you could combine this approach with <a href="https://stackoverflow.com/a/10835703/1194883">the answer @dubiousjim gives</a> to make sure the right test is used for each type.  Not very &quot;pythonic&quot;, but it turns out that NumPy intentionally broke pythonicity in at least this sense.</p>\n<p>If you need to do more than just check if the input is empty, and you\'re using other NumPy features like indexing or math operations, it\'s probably more efficient (and certainly more common) to force the input <em>to be</em> a NumPy array.  There are a few nice functions for doing this quickly —\xa0most importantly <a href="https://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.asarray.html" rel="nofollow noreferrer"><code>numpy.asarray</code></a>.  This takes your input, does nothing if it\'s already an array, or wraps your input into an array if it\'s a list, tuple, etc., and optionally converts it to your chosen <code>dtype</code>.  So it\'s very quick whenever it can be, and it ensures that you just get to assume the input is a NumPy array.  We usually even just use the same name, as the conversion to an array won\'t make it back outside of the current <a href="http://python-textbok.readthedocs.io/en/1.0/Variables_and_Scope.html" rel="nofollow noreferrer">scope</a>:</p>\n<pre><code>x = numpy.asarray(x, dtype=numpy.double)\n</code></pre>\n<p>This will make the <code>x.size</code> check work in all cases I see on this page.</p>\n'}, {'answer_id': 10835703, 'author': 'dubiousjim', 'author_id': 272427, 'author_profile': 'https://Stackoverflow.com/users/272427', 'pm_score': 6, 'selected': False, 'text': '<p>I had written:</p>\n\n<pre><code>if isinstance(a, (list, some, other, types, i, accept)) and not a:\n    do_stuff\n</code></pre>\n\n<p>which was voted -1. I\'m not sure if that\'s because readers objected to the strategy or thought the answer wasn\'t helpful as presented. I\'ll pretend it was the latter, since---whatever counts as "pythonic"---this is the correct strategy. Unless you\'ve already ruled out, or are prepared to handle cases where <code>a</code> is, for example, <code>False</code>, you need a test more restrictive than just <code>if not a:</code>. You could use something like this:</p>\n\n<pre><code>if isinstance(a, numpy.ndarray) and not a.size:\n    do_stuff\nelif isinstance(a, collections.Sized) and not a:\n    do_stuff\n</code></pre>\n\n<p>the first test is in response to @Mike\'s answer, above. The third line could also be replaced with:</p>\n\n<pre><code>elif isinstance(a, (list, tuple)) and not a:\n</code></pre>\n\n<p>if you only want to accept instances of particular types (and their subtypes), or with:</p>\n\n<pre><code>elif isinstance(a, (list, tuple)) and not len(a):\n</code></pre>\n\n<p>You can get away without the explicit type check, but only if the surrounding context already assures you that <code>a</code> is a value of the types you\'re prepared to handle, or if you\'re sure that types you\'re not prepared to handle are going to raise errors (e.g., a <code>TypeError</code> if you call <code>len</code> on a value for which it\'s undefined) that you\'re prepared to handle. In general, the "pythonic" conventions seem to go this last way. Squeeze it like a duck and let it raise a DuckError if it doesn\'t know how to quack. You still have to <em>think</em> about what type assumptions you\'re making, though, and whether the cases you\'re not prepared to handle properly really are going to error out in the right places. The Numpy arrays are a good example where just blindly relying on <code>len</code> or the boolean typecast may not do precisely what you\'re expecting.</p>\n'}, {'answer_id': 27262598, 'author': 'abarnert', 'author_id': 908494, 'author_profile': 'https://Stackoverflow.com/users/908494', 'pm_score': 7, 'selected': False, 'text': '<p><a href="https://stackoverflow.com/a/53522/908494">Patrick\'s (accepted) answer</a> is right: <code>if not a:</code> is the right way to do it. <a href="https://stackoverflow.com/a/53752/908494">Harley Holcombe\'s answer</a> is right that this is in the PEP 8 style guide. But what none of the answers explain is why it\'s a good idea to follow the idiom—even if you personally find it\'s not explicit enough or confusing to Ruby users or whatever.</p>\n\n<p>Python code, and the Python community, has very strong idioms. Following those idioms makes your code easier to read for anyone experienced in Python. And when you violate those idioms, that\'s a strong signal.</p>\n\n<p>It\'s true that <code>if not a:</code> doesn\'t distinguish empty lists from <code>None</code>, or numeric 0, or empty tuples, or empty user-created collection types, or empty user-created not-quite-collection types, or single-element NumPy array acting as scalars with falsey values, etc. And sometimes it\'s important to be explicit about that. And in that case, you know <em>what</em> you want to be explicit about, so you can test for exactly that. For example, <code>if not a and a is not None:</code> means "anything falsey except None", while <code>if len(a) != 0:</code> means "only empty sequences—and anything besides a sequence is an error here", and so on. Besides testing for exactly what you want to test, this also signals to the reader that this test is important.</p>\n\n<p>But when you don\'t have anything to be explicit about, anything other than <code>if not a:</code> is misleading the reader. You\'re signaling something as important when it isn\'t. (You may also be making the code less flexible, or slower, or whatever, but that\'s all less important.) And if you <em>habitually</em> mislead the reader like this, then when you <em>do</em> need to make a distinction, it\'s going to pass unnoticed because you\'ve been "crying wolf" all over your code.</p>\n'}, {'answer_id': 32978062, 'author': 'MrWonderful', 'author_id': 2069807, 'author_profile': 'https://Stackoverflow.com/users/2069807', 'pm_score': 7, 'selected': False, 'text': '<h1>Why check at all?</h1>\n<p>No one seems to have addressed questioning your <em>need</em> to test the list in the first place.  Because you provided no additional context, I can imagine that you may not need to do this check in the first place, but are unfamiliar with list processing in Python.</p>\n<p>I would argue that the <em>most Pythonic</em> way is to not check at all, but rather to just process the list.  That way it will do the right thing whether empty or full.</p>\n<pre><code>a = []\n\nfor item in a:\n    # &lt;Do something with item&gt;\n\n# &lt;The rest of code&gt;\n</code></pre>\n<p>This has the benefit of handling any contents of <strong>a</strong>, while not requiring a specific check for emptiness.  If <strong>a</strong> is empty, the dependent block will not execute and the interpreter will fall through to the next line.</p>\n<p>If you do actually need to check the array for emptiness:</p>\n<pre><code>a = []\n\nif not a:\n    # &lt;React to empty list&gt;\n\n# &lt;The rest of code&gt;\n</code></pre>\n<p>is sufficient.</p>\n'}, {'answer_id': 34558732, 'author': 'Sнаđошƒаӽ', 'author_id': 3375713, 'author_profile': 'https://Stackoverflow.com/users/3375713', 'pm_score': 5, 'selected': False, 'text': '<p>From <a href="https://docs.python.org/3.5/library/stdtypes.html#truth-value-testing">documentation</a> on truth value testing:</p>\n\n<p>All values other than what is listed here are considered <code>True</code></p>\n\n<ul>\n<li><code>None</code></li>\n<li><code>False</code></li>\n<li>zero of any numeric type, for example, <code>0</code>, <code>0.0</code>, <code>0j</code>.</li>\n<li>any empty sequence, for example, <code>\'\'</code>, <code>()</code>, <code>[]</code>.</li>\n<li>any empty mapping, for example, <code>{}</code>.</li>\n<li>instances of user-defined classes, if the class defines a <code>__bool__()</code> or <code>__len__()</code> method, when that method returns the integer zero or bool value <code>False</code>.</li>\n</ul>\n\n<p>As can be seen, empty list <code>[]</code> is <em>falsy</em>, so doing what would be done to a boolean value sounds most efficient:</p>\n\n<pre><code>if not a:\n    print(\'"a" is empty!\')\n</code></pre>\n'}, {'answer_id': 36610301, 'author': 'Tagar', 'author_id': 470583, 'author_profile': 'https://Stackoverflow.com/users/470583', 'pm_score': 4, 'selected': False, 'text': "<pre><code>def list_test (L):\n    if   L is None  : print('list is None')\n    elif not L      : print('list is empty')\n    else: print('list has %d elements' % len(L))\n\nlist_test(None)\nlist_test([])\nlist_test([1,2,3])\n</code></pre>\n\n<p>It is sometimes good to test for <code>None</code> and for emptiness separately as those are two different states. The code above produces the following output:</p>\n\n<pre><code>list is None \nlist is empty \nlist has 3 elements\n</code></pre>\n\n<p>Although it's worth nothing that <code>None</code> is falsy. So if you don't want to separate test for <code>None</code>-ness, you don't have to do that. </p>\n\n<pre><code>def list_test2 (L):\n    if not L      : print('list is empty')\n    else: print('list has %d elements' % len(L))\n\nlist_test2(None)\nlist_test2([])\nlist_test2([1,2,3])\n</code></pre>\n\n<p>produces expected</p>\n\n<pre><code>list is empty\nlist is empty\nlist has 3 elements\n</code></pre>\n"}, {'answer_id': 39469420, 'author': 'Sunil Lulla', 'author_id': 5267848, 'author_profile': 'https://Stackoverflow.com/users/5267848', 'pm_score': 5, 'selected': False, 'text': "<p>You can even try using <code>bool()</code> like this. Although it is less readable surely it's a concise way to perform this.</p>\n<pre><code>    a = [1,2,3];\n    print bool(a); # it will return True\n    a = [];\n    print bool(a); # it will return False\n</code></pre>\n<p>I love this way for the checking list is empty or not.</p>\n<p>Very handy and useful.</p>\n"}, {'answer_id': 40846473, 'author': 'Taufiq Rahman', 'author_id': 5401681, 'author_profile': 'https://Stackoverflow.com/users/5401681', 'pm_score': 5, 'selected': False, 'text': '<p>Here are a few ways you can check if a list is empty:</p>\n\n<pre><code>a = [] #the list\n</code></pre>\n\n<p><strong>1)</strong> The pretty simple pythonic way:</p>\n\n<pre><code>if not a:\n    print("a is empty")\n</code></pre>\n\n<p>In Python, <strong>empty containers</strong> such as lists,tuples,sets,dicts,variables etc are seen as <code>False</code>. One could simply treat the list as a predicate (<em>returning a Boolean value</em>). And  a <code>True</code> value would indicate that it\'s non-empty.</p>\n\n<p><strong>2)</strong> A much explicit way: using the <code>len()</code> to find the length and check if it equals to <code>0</code>:</p>\n\n<pre><code>if len(a) == 0:\n    print("a is empty")\n</code></pre>\n\n<p><strong>3)</strong> Or comparing it to an anonymous empty list:</p>\n\n<pre><code>if a == []:\n    print("a is empty")\n</code></pre>\n\n<p><strong>4)</strong> Another yet <em>silly</em> way to do is using <code>exception</code> and <code>iter()</code>:</p>\n\n<pre><code>try:\n    next(iter(a))\n    # list has elements\nexcept StopIteration:\n    print("Error: a is empty")\n</code></pre>\n'}, {'answer_id': 43083496, 'author': 'AndreyS Scherbakov', 'author_id': 4819357, 'author_profile': 'https://Stackoverflow.com/users/4819357', 'pm_score': 4, 'selected': False, 'text': '<p>Being inspired by <a href="https://stackoverflow.com/questions/53513/how-do-i-check-if-a-list-is-empty/10835703#10835703">dubiousjim\'s solution</a>, I propose to use an additional general check of whether is it something iterable:</p>\n<pre><code>import collections\ndef is_empty(a):\n    return not a and isinstance(a, collections.Iterable)\n</code></pre>\n<p>Note: a string is considered to be iterable—add <code>and not isinstance(a,(str,unicode))</code> if you want the empty string to be excluded</p>\n<p>Test:</p>\n<pre><code>&gt;&gt;&gt; is_empty(\'sss\')\nFalse\n&gt;&gt;&gt; is_empty(555)\nFalse\n&gt;&gt;&gt; is_empty(0)\nFalse\n&gt;&gt;&gt; is_empty(\'\')\nTrue\n&gt;&gt;&gt; is_empty([3])\nFalse\n&gt;&gt;&gt; is_empty([])\nTrue\n&gt;&gt;&gt; is_empty({})\nTrue\n&gt;&gt;&gt; is_empty(())\nTrue\n</code></pre>\n'}, {'answer_id': 45778282, 'author': 'Russia Must Remove Putin', 'author_id': 541136, 'author_profile': 'https://Stackoverflow.com/users/541136', 'pm_score': 8, 'selected': False, 'text': '<blockquote>\n  <h2>Best way to check if a list is empty</h2>\n  \n  <p>For example, if passed the following:</p>\n\n<pre><code>a = []\n</code></pre>\n  \n  <p>How do I check to see if a is empty?</p>\n</blockquote>\n\n<h2>Short Answer:</h2>\n\n<p>Place the list in a boolean context (for example, with an <code>if</code> or <code>while</code> statement). It will test <code>False</code> if it is empty, and <code>True</code> otherwise. For example:</p>\n\n<pre><code>if not a:                           # do this!\n    print(\'a is an empty list\')\n</code></pre>\n\n<h2>PEP 8</h2>\n\n<p><a href="https://www.python.org/dev/peps/pep-0008/#programming-recommendations" rel="noreferrer">PEP 8</a>, the official Python style guide for Python code in Python\'s standard library, asserts:</p>\n\n<blockquote>\n  <p>For sequences, (strings, lists, tuples), use the fact that empty sequences are false.</p>\n\n<pre><code>Yes: if not seq:\n     if seq:\n\nNo: if len(seq):\n    if not len(seq):\n</code></pre>\n</blockquote>\n\n<p>We should expect that standard library code should be as performant and correct as possible. But why is that the case, and why do we need this guidance?</p>\n\n<h2>Explanation</h2>\n\n<p>I frequently see code like this from experienced programmers new to Python:</p>\n\n<pre><code>if len(a) == 0:                     # Don\'t do this!\n    print(\'a is an empty list\')\n</code></pre>\n\n<p>And users of lazy languages may be tempted to do this:</p>\n\n<pre><code>if a == []:                         # Don\'t do this!\n    print(\'a is an empty list\')\n</code></pre>\n\n<p>These are correct in their respective other languages. And this is even semantically correct in Python. </p>\n\n<p>But we consider it un-Pythonic because Python supports these semantics directly in the list object\'s interface via boolean coercion.</p>\n\n<p>From the <a href="https://docs.python.org/3/library/stdtypes.html#truth-value-testing" rel="noreferrer">docs</a> (and note specifically the inclusion of the empty list, <code>[]</code>):</p>\n\n<blockquote>\n  <p>By default, an object is considered true unless its class defines\n  either a <code>__bool__()</code> method that returns <code>False</code> or a <code>__len__()</code> method\n  that returns zero, when called with the object. Here are most of the built-in objects considered false:</p>\n  \n  <ul>\n  <li>constants defined to be false: <code>None</code> and <code>False</code>.</li>\n  <li>zero of any numeric type: <code>0</code>, <code>0.0</code>, <code>0j</code>, <code>Decimal(0)</code>, <code>Fraction(0, 1)</code></li>\n  <li>empty sequences and collections: <code>\'\'</code>, <code>()</code>, <code>[]</code>, <code>{}</code>, <code>set()</code>, <code>range(0)</code></li>\n  </ul>\n</blockquote>\n\n<p>And the datamodel documentation:</p>\n\n<blockquote>\n  <p><a href="https://docs.python.org/3/reference/datamodel.html#object.__bool__" rel="noreferrer"><code>object.__bool__(self)</code></a></p>\n  \n  <p>Called to implement truth value testing and the built-in operation <code>bool()</code>; should return <code>False</code> or <code>True</code>. When this method is not defined,\n  <code>__len__()</code> is called, if it is defined, and the object is considered true if its result is nonzero. If a class defines neither <code>__len__()</code>\n  nor <code>__bool__()</code>, all its instances are considered true.</p>\n</blockquote>\n\n<p>and </p>\n\n<blockquote>\n  <p><a href="https://docs.python.org/3/reference/datamodel.html#object.__len__" rel="noreferrer"><code>object.__len__(self)</code></a></p>\n  \n  <p>Called to implement the built-in function <code>len()</code>. Should return the length of the object, an integer >= 0. Also, an object that doesn’t define a <code>__bool__()</code> method and whose <code>__len__()</code> method returns zero is considered to be false in a Boolean context.</p>\n</blockquote>\n\n<p>So instead of this:</p>\n\n<pre><code>if len(a) == 0:                     # Don\'t do this!\n    print(\'a is an empty list\')\n</code></pre>\n\n<p>or this:</p>\n\n<pre><code>if a == []:                     # Don\'t do this!\n    print(\'a is an empty list\')\n</code></pre>\n\n<p>Do this:</p>\n\n<pre><code>if not a:\n    print(\'a is an empty list\')\n</code></pre>\n\n<h2>Doing what\'s Pythonic usually pays off in performance:</h2>\n\n<p>Does it pay off? (Note that less time to perform an equivalent operation is better:)</p>\n\n<pre><code>&gt;&gt;&gt; import timeit\n&gt;&gt;&gt; min(timeit.repeat(lambda: len([]) == 0, repeat=100))\n0.13775854044661884\n&gt;&gt;&gt; min(timeit.repeat(lambda: [] == [], repeat=100))\n0.0984637276455409\n&gt;&gt;&gt; min(timeit.repeat(lambda: not [], repeat=100))\n0.07878462291455435\n</code></pre>\n\n<p>For scale, here\'s the cost of calling the function and constructing and returning an empty list, which you might subtract from the costs of the emptiness checks used above:</p>\n\n<pre><code>&gt;&gt;&gt; min(timeit.repeat(lambda: [], repeat=100))\n0.07074015751817342\n</code></pre>\n\n<p>We see that <em>either</em> checking for length with the builtin function <code>len</code> compared to <code>0</code> <em>or</em> checking against an empty list is <strong>much</strong> less performant than using the builtin syntax of the language as documented.</p>\n\n<p>Why?</p>\n\n<p>For the <code>len(a) == 0</code> check:</p>\n\n<p>First Python has to check the globals to see if <code>len</code> is shadowed. </p>\n\n<p>Then it must call the function, load <code>0</code>, and do the equality comparison in Python (instead of with C):</p>\n\n<pre><code>&gt;&gt;&gt; import dis\n&gt;&gt;&gt; dis.dis(lambda: len([]) == 0)\n  1           0 LOAD_GLOBAL              0 (len)\n              2 BUILD_LIST               0\n              4 CALL_FUNCTION            1\n              6 LOAD_CONST               1 (0)\n              8 COMPARE_OP               2 (==)\n             10 RETURN_VALUE\n</code></pre>\n\n<p>And for the <code>[] == []</code> it has to build an unnecessary list and then, again, do the comparison operation in Python\'s virtual machine (as opposed to C)</p>\n\n<pre><code>&gt;&gt;&gt; dis.dis(lambda: [] == [])\n  1           0 BUILD_LIST               0\n              2 BUILD_LIST               0\n              4 COMPARE_OP               2 (==)\n              6 RETURN_VALUE\n</code></pre>\n\n<p>The "Pythonic" way is a much simpler and faster check since the length of the list is cached in the object instance header:</p>\n\n<pre><code>&gt;&gt;&gt; dis.dis(lambda: not [])\n  1           0 BUILD_LIST               0\n              2 UNARY_NOT\n              4 RETURN_VALUE\n</code></pre>\n\n<h2>Evidence from the C source and documentation</h2>\n\n<blockquote>\n  <p><a href="https://docs.python.org/2/c-api/structures.html#c.PyVarObject" rel="noreferrer"><code>PyVarObject</code></a></p>\n  \n  <p>This is an extension of <code>PyObject</code> that adds the <code>ob_size</code> field. This is only used for objects that have some notion of length. This type does not often appear in the Python/C API. It corresponds to the fields defined by the expansion of the <code>PyObject_VAR_HEAD</code> macro.</p>\n</blockquote>\n\n<p>From the c source in <a href="https://github.com/python/cpython/blob/master/Include/listobject.h" rel="noreferrer">Include/listobject.h</a>:</p>\n\n<pre><code>typedef struct {\n    PyObject_VAR_HEAD\n    /* Vector of pointers to list elements.  list[0] is ob_item[0], etc. */\n    PyObject **ob_item;\n\n    /* ob_item contains space for \'allocated\' elements.  The number\n     * currently in use is ob_size.\n     * Invariants:\n     *     0 &lt;= ob_size &lt;= allocated\n     *     len(list) == ob_size\n</code></pre>\n\n<h2>Response to comments:</h2>\n\n<blockquote>\n  <p>I would point out that this is also true for the non-empty case though its pretty ugly as with <code>l=[]</code> then <code>%timeit len(l) != 0</code> 90.6 ns ± 8.3 ns, <code>%timeit l != []</code> 55.6 ns ± 3.09, <code>%timeit not not l</code> 38.5 ns ± 0.372. But there is no way anyone is going to enjoy <code>not not l</code> despite triple the speed. It looks ridiculous. But the speed wins out<br>\n  I suppose the problem is testing with timeit since just <code>if l:</code> is sufficient but surprisingly <code>%timeit bool(l)</code> yields 101 ns ± 2.64 ns. Interesting there is no way to coerce to bool without this penalty. <code>%timeit l</code> is useless since no conversion would occur.</p>\n</blockquote>\n\n<p>IPython magic, <code>%timeit</code>, is not entirely useless here:</p>\n\n<pre><code>In [1]: l = []                                                                  \n\nIn [2]: %timeit l                                                               \n20 ns ± 0.155 ns per loop (mean ± std. dev. of 7 runs, 100000000 loops each)\n\nIn [3]: %timeit not l                                                           \n24.4 ns ± 1.58 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)\n\nIn [4]: %timeit not not l                                                       \n30.1 ns ± 2.16 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)\n</code></pre>\n\n<p>We can see there\'s a bit of linear cost for each additional <code>not</code> here. We want to see the costs, <em>ceteris paribus</em>, that is, all else equal - where all else is minimized as far as possible:</p>\n\n<pre class="lang-py prettyprint-override"><code>In [5]: %timeit if l: pass                                                      \n22.6 ns ± 0.963 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)\n\nIn [6]: %timeit if not l: pass                                                  \n24.4 ns ± 0.796 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)\n\nIn [7]: %timeit if not not l: pass                                              \n23.4 ns ± 0.793 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)\n</code></pre>\n\n<p>Now let\'s look at the case for an unempty list:</p>\n\n<pre class="lang-py prettyprint-override"><code>In [8]: l = [1]                                                                 \n\nIn [9]: %timeit if l: pass                                                      \n23.7 ns ± 1.06 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)\n\nIn [10]: %timeit if not l: pass                                                 \n23.6 ns ± 1.64 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)\n\nIn [11]: %timeit if not not l: pass                                             \n26.3 ns ± 1 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)\n</code></pre>\n\n<p>What we can see here is that it makes little difference whether you pass in an actual <code>bool</code> to the condition check or the list itself, and if anything, giving the list, as is, is faster.</p>\n\n<p>Python is written in C; it uses its logic at the C level. Anything you write in Python will be slower. And it will likely be orders of magnitude slower unless you\'re using the mechanisms built into Python directly.</p>\n'}, {'answer_id': 45898755, 'author': 'Vineet Jain', 'author_id': 6761181, 'author_profile': 'https://Stackoverflow.com/users/6761181', 'pm_score': 3, 'selected': False, 'text': "<p>Simply use is_empty() or make function like:- </p>\n\n<pre><code>def is_empty(any_structure):\n    if any_structure:\n        print('Structure is not empty.')\n        return True\n    else:\n        print('Structure is empty.')\n        return False  \n</code></pre>\n\n<p>It can be used for any data_structure like a list,tuples, dictionary and many more. By these, you can call it many times using just <code>is_empty(any_structure)</code>. </p>\n"}, {'answer_id': 49109480, 'author': 'Rahul', 'author_id': 5452365, 'author_profile': 'https://Stackoverflow.com/users/5452365', 'pm_score': 4, 'selected': False, 'text': '<p>If you want to check if a list is empty:</p>\n\n<pre><code>l = []\nif l:\n    # do your stuff.\n</code></pre>\n\n<p>If you want to check whether all the values in list is empty. However it will be <code>True</code> for an empty list:</p>\n\n<pre><code>l = ["", False, 0, \'\', [], {}, ()]\nif all(bool(x) for x in l):\n    # do your stuff.\n</code></pre>\n\n<p>If you want to use both cases together:</p>\n\n<pre><code>def empty_list(lst):\n    if len(lst) == 0:\n        return False\n    else:\n        return all(bool(x) for x in l)\n</code></pre>\n\n<p>Now you can use:</p>\n\n<pre><code>if empty_list(lst):\n    # do your stuff.\n</code></pre>\n'}, {'answer_id': 50362360, 'author': 'Nitin Siwach', 'author_id': 6546694, 'author_profile': 'https://Stackoverflow.com/users/6546694', 'pm_score': 3, 'selected': False, 'text': '<p>The truth value of an empty list is <code>False</code> whereas for a non-empty list it is <code>True</code>.</p>\n'}, {'answer_id': 52771578, 'author': 'Ashiq Imran', 'author_id': 7032887, 'author_profile': 'https://Stackoverflow.com/users/7032887', 'pm_score': 3, 'selected': False, 'text': '<p>Simple way is checking the length is equal zero.</p>\n\n<pre><code>if len(a) == 0:\n    print("a is empty")\n</code></pre>\n'}, {'answer_id': 52772082, 'author': 'HackerBoss', 'author_id': 3081198, 'author_profile': 'https://Stackoverflow.com/users/3081198', 'pm_score': 4, 'selected': False, 'text': '<p>Many answers have been given, and a lot of them are pretty good. I just wanted to add that the check</p>\n\n<pre><code>not a\n</code></pre>\n\n<p>will also pass for <code>None</code> and other types of empty structures. If you truly want to check for an empty list, you can do this:</p>\n\n<pre><code>if isinstance(a, list) and len(a)==0:\n    print("Received an empty list")\n</code></pre>\n'}, {'answer_id': 53127845, 'author': 'Andrey Topoleov', 'author_id': 7306511, 'author_profile': 'https://Stackoverflow.com/users/7306511', 'pm_score': 4, 'selected': False, 'text': "<pre><code>print('not empty' if a else 'empty')\n</code></pre>\n<p>a little more practical:</p>\n<pre><code>a.pop() if a else None\n</code></pre>\n<p>and the shortest version:</p>\n<pre><code>if a: a.pop() \n</code></pre>\n"}, {'answer_id': 53169502, 'author': 'Trect', 'author_id': 9789097, 'author_profile': 'https://Stackoverflow.com/users/9789097', 'pm_score': 3, 'selected': False, 'text': "<p>From python3 onwards you can use</p>\n\n<pre><code>a == []\n</code></pre>\n\n<p>to check if the list is empty</p>\n\n<p>EDIT : This works with python2.7 too.. </p>\n\n<p>I am not sure why there are so many complicated answers.\nIt's pretty clear and straightforward</p>\n"}, {'answer_id': 53926417, 'author': 'Andy Jazz', 'author_id': 6599590, 'author_profile': 'https://Stackoverflow.com/users/6599590', 'pm_score': 4, 'selected': False, 'text': "<p>To check whether a list is empty or not you can use two following ways. But remember, we should avoid the way of explicitly checking for a type of sequence (it's a <strong>less Pythonic</strong> way):</p>\n<pre><code>def enquiry(list1):\n    return len(list1) == 0\n\n# ––––––––––––––––––––––––––––––––\n\nlist1 = []\n\nif enquiry(list1):\n    print(&quot;The list isn't empty&quot;)\nelse:\n    print(&quot;The list is Empty&quot;)\n\n# Result: &quot;The list is Empty&quot;.\n</code></pre>\n<p>The second way is a <strong>more Pythonic</strong> one. This method is an implicit way of checking and much more preferable than the previous one.</p>\n<pre><code>def enquiry(list1):\n    return not list1\n\n# ––––––––––––––––––––––––––––––––\n\nlist1 = []\n\nif enquiry(list1):\n    print(&quot;The list is Empty&quot;)\nelse:\n    print(&quot;The list isn't empty&quot;)\n\n# Result: &quot;The list is Empty&quot;\n</code></pre>\n"}, {'answer_id': 54065002, 'author': 'l. zhang', 'author_id': 10874195, 'author_profile': 'https://Stackoverflow.com/users/10874195', 'pm_score': 4, 'selected': False, 'text': '<p>We could use a simple <em>if else</em>:</p>\n<pre class="lang-py prettyprint-override"><code>item_list=[]\nif len(item_list) == 0:\n    print(&quot;list is empty&quot;)\nelse:\n    print(&quot;list is not empty&quot;)\n</code></pre>\n'}, {'answer_id': 54612063, 'author': 'Vikrant', 'author_id': 1302617, 'author_profile': 'https://Stackoverflow.com/users/1302617', 'pm_score': 5, 'selected': False, 'text': '<p>Method 1 (preferred):</p>\n<pre><code>if not a:\n   print (&quot;Empty&quot;)\n</code></pre>\n<p>Method 2:</p>\n<pre><code>if len(a) == 0:\n   print(&quot;Empty&quot;)\n</code></pre>\n<p>Method 3:</p>\n<pre><code>if a == []:\n  print (&quot;Empty&quot;)\n</code></pre>\n'}, {'answer_id': 55833259, 'author': 'Vedran Šego', 'author_id': 1667018, 'author_profile': 'https://Stackoverflow.com/users/1667018', 'pm_score': 3, 'selected': False, 'text': '<p>What brought me here is a special use-case: I actually wanted a <em>function</em> to tell me if a list is empty or not. I wanted to avoid writing my own function or using a lambda-expression here (because it seemed like it should be simple enough):</p>\n\n<pre><code>foo = itertools.takewhile(is_not_empty, (f(x) for x in itertools.count(1)))\n</code></pre>\n\n<p>And, of course, there is a very natural way to do it:</p>\n\n<pre><code>foo = itertools.takewhile(bool, (f(x) for x in itertools.count(1)))\n</code></pre>\n\n<p>Of course, do <strong>not</strong> use <code>bool</code> in <code>if</code> (i.e., <code>if bool(L):</code>) because it\'s implied. But, for the cases when "is not empty" is explicitly needed as a function, <code>bool</code> is the best choice.</p>\n'}]
['https://Stackoverflow.com/questions/53513', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4872/']