- 1
Can someone explain to me how this works? (Simple challenge question)
so I was doing a challenge and one of the questions were a = [1,2] b = a a.append (3) print(len (b)) where the answer was 3. So, how come the number appends to b when it was called after b was given the same values of a? edit: fixed the question
7 Respuestas
+ 1
If you want a and b to be equal, but not change them both at the same time, you would need to do something like:
a = [1, 2]
b = []
for i in a:
b.append(i)
a.append(3)
print(len(b))
//output 2
or more simply:
a = [1, 2]
b = [1, 2]
a.append(3)
print(len(b))
//output 2
You need to tell the computer you want to make two separate lists, or it will assume you mean one list that has two names, a and b.
+ 1
That's really interesting. Thanks for pointing that out.
0
That should print 3 if you give it print(len(a)) or print(len(b)) or print(a[2]) or print(b[2]), but print(b) should give [1, 2, 3], not 3. The question was stated wrong.
edit: to fix the mistake that OP made in my comment by fixing the post.
0
Ethan the question wasn't wrong because the final line says print(len(b)) so, as you said it should give 3. That's because the 2 variables(a and b) are linked so when you change the value of one of them the other will follow the previous rule given (a=b) and update itself
0
no ethan was right, I originally left put the len () by accident, so I edited it, hence the 'edit' comment. So, when you equate one variable to another, whatever happens to the original happens to the 'copy'?
0
There is no copy. declaring a makes a list and a pointer that means a points to that list. b = a then says that b also points to the same thing, so when you change a, you change the list that both a and b are pointing to, and when you call len(b) it finds the length of the changed list.
0
Sorry didn't see the edited text.
But, wait a sec. I'm seeing now that works only with lists or maybe specific comands. If you try:
a=5
b=a
a+=1
print(b)
It returns 5