How do I know if a list is empty in Python?

Asked

Viewed 15,191 times

4

I’m starting at the python and always end up appearing some doubts at the beginning.

I need to know how to test if a list is empty.

As I always say, I come from PHP.

So I used to make these shapes:

count($array) == 0

empty($array);

!$array

How to do this in python?

Example:

 a = [1, 2, 3]
 b = []

 # a é vazio?
 # b é vazio?

2 answers

9


I suppose a a list:

a = []

Test yourself like this:

if not a:
    # Condição se for vazio.

Yes. Very simple.

  • 2

    +1. Very, very simple indeed!

  • 2

    Adding, "if not" is executed when the value is zero, empty or false.

4

Just for curiosity purposes. You can also do it in the "ugly way".

Still supposing that a is a list

a = []

if len(a) == 0:
    # Condição se for vazio

if a == []:
    # Condição ser for vazio
  • 1

    +1 for the ugly way it is. It is not very common in Python, but it is familiar in PHP

  • 1

    Bleh. Tosqueira.

  • I thought the impact would be less, since he program in PHP @Ciganomorrisonmendez

  • 3

    @jbueno Think about quality of life, young.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.