0

I was going through the book "Deep Learning with Python" and came across the following:

def smooth_curve(points, factor=0.9):
     smoothed_points = []
     for point in points:
          if smoothed_points:
                previous = smoothed_points[-1]
                smoothed_points.append(previous * factor + point * (1 - factor))
          else:
               smoothed_points.append(point)
     return smoothed_points
smooth_mae_history = smooth_curve(average_mae_history[10:])

I've never seen this notation before, the 4th line of code "if smoothed_points". Smoothed_points is a list. I don't understand how lists can evaluate to either true or false in some orderly way.

  • " I don't understand how lists can evaluate to either true or false in some orderly way." *every object in Python can be considered truthy or falsy* For built-in container types, empty containers are falsy, non-empty containers are truthy. – juanpa.arrivillaga Apr 13 '21 at 22:06

1 Answers1

2

Non-empty collections like lists are always considered True in Python.

From the documentation:

Any object can be tested for truth value, for use in an if or while condition or as operand of the Boolean operations below.

By default, an object is considered true unless its class defines either a __bool__() method that returns False or a __len__() method that returns zero, when called with the object. Here are most of the built-in objects considered false:

  • constants defined to be false: None and False.
  • zero of any numeric type: 0, 0.0, 0j, Decimal(0), Fraction(0, 1) empty sequences and
  • collections: '', (), [], {}, set(), range(0)

You're right that this could seem a little weird in some circumstances:

if [False]:
  print(True) # Prints True

It's a design decision, ensuring that (in your words) "lists can evaluate to either true or false in some orderly way". The orderly way the designers of Python have chosen is that empty objects are generally False and objects with stuff in them are generally True.

ASGM
  • 11,051
  • 1
  • 32
  • 53