Iustinian Olaru
Iustinian Olaru

Reputation: 1337

What does an if statement evaluate a list to?

What does an if statement on a list in python evaluate to? I remember reading somewhere that if you do it on an empty list if evaluates to false and otherwise it evaluates to True. Is there any reason to check for the list length also?

For example:

list = [10]*10

if list:
    print("First check)

if list and len(list):
    print("Second check")

What do the above two checks look at? They both evaluate to true.

Upvotes: 1

Views: 415

Answers (4)

Juhi Dhameliya
Juhi Dhameliya

Reputation: 169

if list: means list is not empty and in your code it contains 10 elements. So, the condition is always going to be true. Also, length of your list is 10. so, second condition is also true. so, no difference..

Upvotes: 0

guidot
guidot

Reputation: 5333

The definite answer is in the Python documentation:

Only the empty list is false, even a list containing just one Noneis true. So the length test adds nothing to result.

Upvotes: 1

Mureinik
Mureinik

Reputation: 311808

An empty list is a false-y. There's no need to explicitly check the length too.

Upvotes: 3

Raymond Reddington
Raymond Reddington

Reputation: 1837

if list means:

  1. if list != []
  2. if list != None

Upvotes: 1

Related Questions