0

I have a piece of code as follow:

def min_edit_dist_align(source, target):
    n = len(source)
    m = len(target)
    trace = [[[] for i in range(m + 1)] for j in range(n + 1)]
    for i in range(1, n + 1):
      print(i-1)
      print(trace)
      trace[i][0] = trace[i-1][0].append((i-1, 0))

By reading this code, I expect that the 2D array will start to be modified from trace[1][0], and iteratively add more tuple for trace[2][0] to trace[n][0].

But instead, what I received was:

0
[[[], [], [], [], [], [], [], [], [], []], [[], [], [], [], [], [], [], [], [], []], [[], [], [], [], [], [], [], [], [], []], [[], [], [], [], [], [], [], [], [], []], [[], [], [], [], [], [], [], [], [], []], [[], [], [], [], [], [], [], [], [], []], [[], [], [], [], [], [], [], [], [], []], [[], [], [], [], [], [], [], [], [], []], [[], [], [], [], [], [], [], [], [], []], [[], [], [], [], [], [], [], [], [], []]]
1
[[[(0, 0)], [], [], [], [], [], [], [], [], []], [None, [], [], [], [], [], [], [], [], []], [[], [], [], [], [], [], [], [], [], []], [[], [], [], [], [], [], [], [], [], []], [[], [], [], [], [], [], [], [], [], []], [[], [], [], [], [], [], [], [], [], []], [[], [], [], [], [], [], [], [], [], []], [[], [], [], [], [], [], [], [], [], []], [[], [], [], [], [], [], [], [], [], []], [[], [], [], [], [], [], [], [], [], []]]
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-289-840ed3901b1b> in <module>()
----> 1 min_edit, trace = min_edit_dist_align("intention", "execution")
      2 print(min_edit)
      3 print(trace)

<ipython-input-288-4267b6331b53> in min_edit_dist_align(source, target)
     16       print(i-1)
     17       print(trace)
---> 18       trace[i][0] = trace[i-1][0].append((i-1, 0))
     19 
     20     for j in range(1, m+1):

AttributeError: 'NoneType' object has no attribute 'append'

Can anyone please explain to me why the element trace[1][0] becomes None and the iterations does not start modify the array from trace[0][0]? I am kinda new to Python.

blank
  • 37
  • 1
  • 7
  • 1
    `append` in Python does not return a value. It simply appends an element to the indicted array, but returns `None`. – Frank Yellin Nov 26 '21 at 18:08
  • @FrankYellin I see, and solved the problem there. Thank you very much! – blank Nov 26 '21 at 18:29
  • Does this answer your question? [Why does list.append evaluate to false in a boolean context?](https://stackoverflow.com/questions/1682567/why-does-list-append-evaluate-to-false-in-a-boolean-context) (different question, but exact same answer) – wjandrea Nov 27 '21 at 00:40

0 Answers0