+ 2

"strange" for loop behaviour [solved]

Can someone explain what happens in the code below? a = [] b = [a, a, a] for x in b: n = len(x) x.append(n) print(b[0]) # --> [0, 1, 2] Why does x.append(n) also append n to a? Something similar happens when I write x+=['test'] However, if I write x=['test'] or x='test' a does not change

26th Feb 2021, 12:12 PM
gilex
gilex - avatar
3 ответов
+ 4
gilex the logic goes like this: a = [] b = [a, a, a] #Here, you put the list a in list b! It's a list in a list! for x in b: #Here, the for loop iterates for each element in b, which is the list a three times! (since b contains list a three times) so, n is list a. n = len(x) #The same as n = len(a) x.append(n) #Since x is list a, it will append n! print(b[0]) # b[0] or the first element of b is list a, so it prints list a, which is [0,1,2]! Don't worry, this is only because you put a list inside a list! I didn't even know you can do that! 😅 Happy programming! :)
26th Feb 2021, 12:24 PM
TheCoder
0
Thank you for your explanation and have a great day😀
26th Feb 2021, 12:32 PM
gilex
gilex - avatar
0
gilex you're welcome and thanks! Have a great day as well 😊
26th Feb 2021, 12:37 PM
TheCoder