Nested empty loop description

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

 x = [] for i in range(3): x = [x + x] A.[[[[]]]]. B.[[[],[]]]. C.[[[[],[]],[[],[]]]]. D.[[],[],[],[],[],[]] 

Answer: c, can someone explain why this is happening? I understand 2/3 of the iteration, but I donโ€™t understand how it happened from 1st to 2nd, why it didnโ€™t become [[],[]]

+6
source share
3 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! [[]] not an empty list, it is a list containing an empty list

Second run :

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

Third run :

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

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

+14
source
 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] 

exit:

 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] = [[[[], []], [[], []]]] 
+8
source

We go through the code, should we:

  • x = [] : create an empty list named x
  • for i in range(3) : repeat the code below three times:
    • x = [x + x] reassign the x value to the current x value plus the current x value and wrap it in a list.

Essentially, each iteration happens in the fact that your list is nested one level, and the list inside your list is currently becoming a subordinate list of this nested list.

In fuzzy terms, the simplest explanation would be: at each iteration of the for loop, the value of the variable x is assigned to the value of two nested, which can also contain two other nested lists within the same list.

Here is an illustration showing the value of x at each iteration for -loop:

 >>> # x is empty >>> x = [] >>> >>> # 1st iteration >>> x = [x + x] >>> # x >>> x [[]] # your list is nested by one level >>> >>> # 2nd iteration >>> x = [x + x] >>> # x >>> x [[[], []]] # your list is nested by three levels >>> # 3rd iteration >>> x = [x + x] >>> # x >>> x [[[[], []], [[], []]]] # your list is nested by four levels >>> 

If the above illustration is too crowded, here is a shorter one:

 First iteration Value of x: [[]] Second iteration Value of x: [[[], []]] Third iteration Value of x: [[[[], []], [[], []]]] 

I also find creating a tree type structure from a nested list, helps to understand what happens better:

 [ # 1st level [ # second level [ # third level [], # fourth level [] ], [ [], [] # fourth level ] # third level ] # second level ] # 1st level 
+3
source

Source: https://habr.com/ru/post/1011532/


All Articles