Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (45.3k points)

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.

1 Answer

0 votes
by (16.8k points)

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

Related questions

0 votes
1 answer
0 votes
2 answers
asked May 30, 2019 in Python by Anvi (10.2k points)
0 votes
4 answers
0 votes
4 answers
0 votes
1 answer
asked Aug 24, 2019 in Python by Sammy (47.6k points)

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...