1
release_dates = [1897.0, 1998.0, 2000.0, 1948.0, 1962.0, 1950.0, 1975.0, 1960.0,
                 2017.0, 1937.0, 1968.0, 1996.0, 1944.0, 1891.0, 1995.0, 1948.0, 
                 2011.0, 1965.0, 1891.0, 1978.0]

def min_max_normalize(lst):
  minimum = min(lst)
  maximum = max(lst)
  normalized = []
  
  for value in lst:
    normalized_num = (value - minimum) / (maximum - minimum)
    normalized+=(normalized_num)
  
  return normalized

print(min_max_normalize(release_dates))

A bit confused as to why I can't use += in the above scenario while I can use .append()

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
Gojilla
  • 81
  • 1
  • 7
  • `normalized` is a list. You cannot perform an operation on a list. – Parth Shah Jul 07 '20 at 09:39
  • 1
    `+=` is used for strings, ints, floats... not lists. – samthegolden Jul 07 '20 at 09:40
  • 1
    You should do `normalized += [normalized_num]` – MarshalSHI Jul 07 '20 at 09:40
  • 2
    @samthegolden `+=` is for anything that implements [`__iadd__`](https://docs.python.org/3/reference/datamodel.html#object.__iadd__) (or `__add__`/`__radd__`, as a fallback). You *can* use it on a list. – jonrsharpe Jul 07 '20 at 09:41
  • 1
    The += is an overloaded operator. If you use `list` and `+=` you can only add another `iterable` to it: `normalized += [ 42.0 ]` is fine, `normalized += 42.0` is not. And `normalized += map(str, [42,42,42])` would be ok as well (as its iterable) – Patrick Artner Jul 07 '20 at 09:41
  • Hi, then use list comprehension normalized = [(value - minimum) / (maximum - minimum) for value in lst ] this should work well. No need for the explicit for loop. Best regards – smile Jul 07 '20 at 09:42

1 Answers1

0

Using += on a list is equivalent to extend, not append, so this line

normalized += (normalized_num)

should be

normalized += [normalized_num]

to make it a list with one element. You could also extend with a tuple, but for a one-elemented tuple you'd have to use (normalized_num,), whereas (normalized_num) is just the same as normalized_num, i.e. a float.

tobias_k
  • 81,265
  • 12
  • 120
  • 179