Home>
I want to know
// import Various things that must be written in Java are not written. Extracting only the part of the movement I want to know
List<List<String>>output = new ArrayList<List<String>>();
List<String>list = new ArrayList<String>();
for (int k = 0;k<2;k ++) {
    list.add (array 1 [k]);
    list.add (array2 [k]);
    list.add (string1 + string2);
    output.add (list);
}


What is the content of output in the above code? The contents of output are

[[array 1 [0], array 2 [0], character string 1 + character string 2], [array 1 [1], array 2 [1], character string 1 + character string 2] ]


Is this correct?
I want to do the same thing in Python

lst = []
output = [] []
for k in range (2):
    lst.append (array 1 [k])
    lst.append (array 2 [k])
    lst.append (string1 + string2)
    output.append (lst)


I thought it was this code, but the contents of output were different from what I thought.
How do you write Python code with the same content as Java above?

  • Answer # 1

    The original java code itself,

    [[array 1 [0], array 2 [0], string 1 + string 2, array 1 [1], array 2 [1], string 1 + string 2],
     [Array 1 [0], array 2 [0], character string 1 + character string 2, array 1 [1], array 2 [1], character string 1 + character string 2]]
    I think you can get

    , but ...


    Reason for that.

    The inner list is declared outside the loop. It will not return to the empty list at the momentoutput.append (lst)is given.

    The list is a so-called reference type in both java and python, and does not hold the state whenoutput.append (lst)is used. You can think of append as an operation that only adds a pointer to an object.