Why "print a.append(1)" doesnt work?


#1

Hi experts,

a = []
a.append(1)
print a
This works

but why
a = []
print a.append(1)
doesnt work?

are there a reason behind it or I should just memerize this situation doesnt work.
THX


#3

If the append method doesn’t return a list, perhaps what it did wasn’t to create a new list with the additional value in it, perhaps it modified the original list instead.

It’s not that it doesn’t work, it certainly does something, but you have to “connect” things in matching ways when you combine steps.

It’s like if Lisa puts her homework on the left chair and when Bob tries to steal it from the right chair it isn’t there. Why doesn’t it work? She put it somewhere else, those actions didn’t line up in a way that produced the desired final outcome


#4

From my understanding,
You are saying a.append(1) only do an action to add (1) to the a list.
But do not return the a list?

So in my imagination, the list is like a box, when .append(), it “only” do something to the box.
When I call print “the action”, the computer can only print out some “box” not “action to the box”.

Why I have this kind of question is I know I can do some combination of print for example:
print “He’s %d inches tall.” % my_height
in this case, because their is already a box there. so the % action make sense to the computer?

This is very abstract to me. Thank you for your patience.


#5

Yes, calling the list’s append method is like asking the list to do something

It COULD have returned the same list or a copy with the new element, but it doesn’t.

And let me add that I like that it doesn’t return the list, because then it’s easy to assume that the original wasn’t changed, it’s much better to only present the result in one location and in a way that makes it clear what it does.

In contrast, javascript (which is awful) does things like:

stuff = [1, 2, 3];
console.log(stuff.reverse());  // [3, 2, 1] yay, I got a new value back, reversed

Great, it created a new array that is reversed and returned it, right?

No, it reversed the original, and also returned the original.

console.log(stuff);  // [3, 2, 1]  wait what, I didn't ask for this...

#6

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.