0

I don't get it why here the result is [[0 0] [0 0]]; Here is the code:

def create_table(m,n):
    t=[]
    one_line=[]
    for i in range(0,m):
        one_line.append(0)
    for i in range(0,n):
        t.append(one_line)
    return t

print(create_table(2,2));

After first iteration in one_line we have [0] and in t [[0]].

After the second iteration, where i=2 we have one_line = [0 0] and in t = [[0 0] [0 0]]. But why is not t=[[0] [0 0]] because the previous t was [[0]] not [[0 0] [0 0]].

Any explanation?

5
  • I don't understand it………what do you mean by "the previous t"? Commented Apr 14, 2016 at 11:16
  • one_line.append(0) every time append a 0 on list . Commented Apr 14, 2016 at 11:18
  • we have the first t from the first iteration where it was [[0]]. Commented Apr 14, 2016 at 11:18
  • @IrinaFarcau Make sure the code above is what it is. Commented Apr 14, 2016 at 11:19
  • 1
    i think, you have understood python loop false. the second loop will run after the the first loop is finished. the previous t of your code was [[0, 0]] and not [[0]] Commented Apr 14, 2016 at 11:25

2 Answers 2

1

You have defined two for loops:

  1. First you loop twice through the first for loop, creating one_line=[0,0]
  2. Then you loop trough the second loop (twice), thus appending [0,0] twice to t thus ending up with t=[[0,0],[0,0]]
Sign up to request clarification or add additional context in comments.

Comments

0

So run your function call create_table(2, 2)

create_table(2, 2):

set: m = 2, n = 2

t = []
one_line = []

define: t = [], one_line = []

for i in range(0,m):

for i in [0, 1]

with i = 0

one_line.append(0)

one_line = [0]

with i = 1

one_line.append(0)

one_line = [0, 0]

for i in range(0,n):

for i in (0, 1)

with i = 0

t.append(one_line)

t = [[0, 0]]

with i = 1

t.append(one_line)

t = [[0, 0], [0, 0]]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.