Irina Farcau
Irina Farcau

Reputation: 167

dictionaries create table python

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?

Upvotes: 0

Views: 62

Answers (2)

qvpham
qvpham

Reputation: 1938

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]]

Upvotes: 0

BartDur
BartDur

Reputation: 1106

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]]

Upvotes: 1

Related Questions