+ 12
Can you please explain the output of this code?
a = [] b = [a, a, a] for x in b: n = len(x) x.append(n) print(b[0]) Answer is [0, 1, 2]
11 ответов
+ 6
All three elemets of list “b” actually are the only one element - list “a”, there are just three references to list “a”.
When “for loop” takes first element - list “a” - this element is empty, so len(x)=0. It appends the integer 0 into the list “a”.
Then “for loop” takes second element of list “b” - the same list “a”, which already has one element inside it - the integer 0. That’s why at this point len(x)=1. We append the integer 1 into list “a”, so list “a” has two elements inside, so a==[0,1].
As you guess at the third iteration len(x)==2, it appends integer 2 into list “a”.
At the end, when you see print(b[0]), b[0] is list “a”, which now contains 0,1 and 2 inside.
Hope it is clear=)
+ 6
For x in b means a
At first len(x=a)=0 , so n=0 and 0 append to a, so now a=[0]
For Second len(x=a) = 1, so n=1 and 1 append to a , so a=[0,1]
For Third one len(a)=2, so n=2 and 2 append to a , so now a=[0,1,2]
Now we know b[0]=b[1]=b[2]=a
And a =[0,1,2]
+ 6
Yes I made a mistake and I edited it Mikhail
+ 6
Continuing Jente's explanation:
0. b = [[], [], []]
1. b = [[0], [0], [0]]
2. b = [[0, 1], [0, 1], [0, 1]]
3. b = [[0, 1, 2], [0, 1, 2], [0, 1, 2]]
+ 6
All three elemets of list “b” actually are the only one element - list “a”, there are just three references to list “a”.
When “for loop” takes first element - list “a” - this element is empty, so len(x)=0. It appends the integer 0 into the list “a”.
Then “for loop” takes second element of list “b” - the same list “a”, which already has one element inside it - the integer 0. That’s why at this point len(x)=1. We append the integer 1 into list “a”, so list “a” has two elements inside, so a==[0,1].
As you guess at the third iteration len(x)==2, it appends integer 2 into list “a”.
At the end, when you see print(b[0]), b[0] is list “a”, which now contains 0,1 and 2 inside.
Continuing Jente's explanation:
0. b = [[], [], []]
1. b = [[0], [0], [0]]
2. b = [[0, 1], [0, 1], [0, 1]]
3. b = [[0, 1, 2], [0, 1, 2], [0, 1, 2]]
For x in b means a
At first len(x=a)=0 , so n=0 and 0 append to a, so now a=[0]
For Second len(x=a) = 1, so n=1 and 1 append to a , so a=[0,1]
For Third one len(a)=2, so n=2 and 2 append to a
+ 5
+ 4
I tried to rewrite and analyze it:
a = []
b = [a]*3
for x in b:
n = len(x)
x.append(n)
print(b[0])
Answer is [0, 1, 2]
So, if we change to b = [a]*4,
the answer would be:
[0, 1, 2, 3]
to b = [a]*5
the answer would be
[0, 1, 2, 3, 4]
and so on.
Also print(b) give us all the list ([0, 1, 2, ... n-1] n times)
+ 3
It's simple
List b has sublist a three times...
b = [ [] [] [] ]. Initially
In the for loop a gets appended with length of a i.e. 0
Now b = [ [0] [0] [0] ]
+ 2
first
0
6969
0
I have no idea ;)