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 [[],[]]
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] = [ [[[[], []]], [[[], []]]] ]
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] = [[[[], []], [[], []]]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With