Skip to content Skip to sidebar Skip to footer

How To Fix The List Of Output From For-loop Always Store The Last Value Of Last Index In Python

I try to store the number of weekofyear from the list of data named date_range which stored the data such as date_range[1] = DatetimeIndex(['2020-03-02', '2020-03-03', '2020-03-04'

Solution 1:

  1. 0 is an int object (in Python, everything is an object, remember). Let's call this int object as the "ZERO_OBJECT".
  2. [0] is a list object having one element, and that element is a reference to the "ZERO_OBJECT". Let's call this list object "LIST_1"
  3. [0]*35 creates another list object, consisting of 35 references to the same "ZERO_OBJECT". (That's how the * operator works in Python). Let's call this new list object "LIST_2"
  4. [[0]*35] is yet another list object having one element, and that element is a reference to the above object "LIST_2". Let's call this new list object "LIST_3"
  5. [[0]*35]*28 creates another list object, consisting of 28 elements, but each of those 28 elements is a reference to the same object "LIST_3". As I said above, that is how the * operator works. (And you thought those 28 elements were references to independent copies of "LIST_3"). This is definitely not what you wanted. Because, when you update one reference to "LIST_3", you will see it reflected via all other references to "LIST_3".

To fix this, use this code:

weeknumber = []
for i in range(28):
    weeknumber.append([])
    for j in range(35)):
        weeknumber[i].append(pd.Timestamp(date_range[i][j]).weekofyear)

Post a Comment for "How To Fix The List Of Output From For-loop Always Store The Last Value Of Last Index In Python"