Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested brackets empty loop explanation

Tags:

python

What is the value of x after the following code is executed?

x = []
for i in range(3):
    x = [x + x]

A.[[[[]]]].
B.[[[],[]]].
C.[[[[],[]],[[],[]]]].
D.[[],[],[],[],[],[]]

The answer is c, can someone explain why this happens? I understand the 2/3 iteration, but don't understand how it went from 1st to 2nd, as in why it didn't become [[],[]]

like image 591
Chrismon Chin Avatar asked Oct 21 '16 03:10

Chrismon Chin


2 Answers

I used extra spaces for a clear expression.

First Run :

x + x = [] + [] = []
empty list + empty list is another empty list

so [x + x] = [ [] ]
attention! [[]] is not an empty list, it is a list containing an empty list

Second Run:

x + x = [[]] + [[]] = [[], []]
so [x + x] = [ [[], []] ]

Third Run :

x + x = [[[], []]] + [[[], []]] = [[[[], []]], [[[], []]]]

so [x + x] = [ [[[[], []]], [[[], []]]] ]

like image 89
Pham Avatar answered Nov 02 '22 13:11

Pham


x = []
for i in range(3):
    print('\ni =', i)
    print('x =' , x)
    print('x + x =', x + x)
    print('[x + x] =', [x + x])
    x = [x + x]

output:

i = 0
x = []
x + x = []  # Here is why. If you extend [] by [], you get []. 
[x + x] = [[]]  # And we wrap the result.

i = 1
x = [[]]
x + x = [[], []]
[x + x] = [[[], []]]

i = 2
x = [[[], []]]
x + x = [[[], []], [[], []]]
[x + x] = [[[[], []], [[], []]]]
like image 7
Mikhail M. Avatar answered Nov 02 '22 11:11

Mikhail M.