Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if list is empty without using the `not` command

Tags:

How can I find out if a list is empty without using the not command?
Here is what I tried:

if list3[0] == []:  
    print("No matches found")  
else:  
    print(list3)

I am very much a beginner so excuse me if I do dumb mistakes.

like image 975
user2240288 Avatar asked Apr 15 '13 17:04

user2240288


People also ask

How do you check a list is empty or not?

Using len() With Comparison Operator In the code above, len(py_list) == 0 will be true if the list is empty and will will be redirected to the else block. This also allows you to set other values as well, rather than relying on 0 being converted as False . All other positive values are converted to True .

How do you check a list is empty or not in Java?

The isEmpty() method of List interface in java is used to check if a list is empty or not. It returns true if the list contains no elements otherwise it returns false if the list contains any element.

Is not empty in Python?

Using len() function To check an empty string in Python, use the len() function; if it returns 0, that means the string is empty; otherwise, it is not.

How check list is empty or not in C#?

Now to check whether a list is empty or not, use the Count property. if (subjects. Count == 0) Console.


2 Answers

In order of preference:

# Good
if not list3:

# Okay
if len(list3) == 0:

# Ugly
if list3 == []:

# Silly
try:
    next(iter(list3))
    # list has elements
except StopIteration:
    # list is empty

If you have both an if and an else you might also re-order the cases:

if list3:
    # list has elements
else:
    # list is empty
like image 159
John Kugelman Avatar answered Sep 20 '22 06:09

John Kugelman


You find out if a list is empty by testing the 'truth' of it:

>>> bool([])
False
>>> bool([0])     
True

While in the second case 0 is False, but the list [0] is True because it contains something. (If you want to test a list for containing all falsey things, use all or any: any(e for e in li) is True if any item in li is truthy.)

This results in this idiom:

if li:
    # li has something in it
else:
    # optional else -- li does not have something 

if not li:
    # react to li being empty
# optional else...

According to PEP 8, this is the proper way:

• For sequences, (strings, lists, tuples), use the fact that empty sequences are false.

Yes: if not seq:
     if seq:

No: if len(seq)
    if not len(seq)

You test if a list has a specific index existing by using try:

>>> try:
...    li[3]=6
... except IndexError:
...    print 'no bueno'
... 
no bueno

So you may want to reverse the order of your code to this:

if list3:  
    print list3  
else:  
    print "No matches found"
like image 25
dawg Avatar answered Sep 22 '22 06:09

dawg