0

Why does this code give n instead of y?

In one of the code challenges, there is this exercise, but I don't understand why the answer is n instead of y? "What is the output of this code a,b=[1,2],[1,2] if id(a)==id(b): print("y") else: print("n") (Code by Paolo Di Paolo)" Can someone please explain? Thanks!

20th Aug 2024, 1:52 PM
Gwendolyn Vervaeke
Gwendolyn Vervaeke - avatar
4 ответов
+ 11
Gwendolyn Vervaeke , list `a` and list `b` are not the same object, so they have a different id. run the code below to see this effect here: a,b=[1,2],[1,2] print(f'a: {a}, b: {b}') print(f'id a: {id(a)}, id b: {id(b)}') if id(a)==id(b): print("y") else: print("n")
20th Aug 2024, 2:22 PM
Lothar
Lothar - avatar
+ 3
if you just want to compare if two lists have the same length, same values, and in the same order, you can do a,b = [1,2],[1,2] if len(a)==len(b) and all(x == y for (x,y) in zip(a,b)): print('y') else: print('n')
21st Aug 2024, 1:39 AM
Bob_Li
Bob_Li - avatar
+ 1
Godslove Iwuamadi , this is not the place to say hello. > *q&a* section is meant for raising coding related questions and discussions. > anything else can be posted in the `feed` in the `community` section.
21st Aug 2024, 10:45 AM
Lothar
Lothar - avatar
0
Hello
21st Aug 2024, 10:27 AM
Godslove Iwuamadi