Python Forum
Newbie lists problem - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Newbie lists problem (/thread-14689.html)



Newbie lists problem - LedDiode - Dec-12-2018

Hi,

I'm trying to learn Python by myself, and while trying some code to learn more about lists I tried something that didn't output what I did except to... Can you help me and furthermore explain me the reason why it didn't work.


empty_list = []
first_var = 1

filled_list = empty_list.append(first_var)
print(filled_list)
It prints me out "None" instead of [1]…

Thanks a lot


RE: Newbie lists problem - ichabod801 - Dec-12-2018

The append method doesn't return anything (or rather it returns None), it modifies the list you appended to. You want to print empty_list.

This is an important thing about lists: they can be changed in place. You'll note that string can't, which is why most of the string methods return a new string.


RE: Newbie lists problem - LedDiode - Dec-13-2018

Okay! If I've understood It's like if I wrote:

filled_list = None
Because it doesn't take in count the append() method to print it out ?

Thank you very much :)


RE: Newbie lists problem - ichabod801 - Dec-13-2018

Well, it does take into account the append method. That's where the None came from. It's just that the actual appending is done to empty_list. That is, after line 4, empty_list is [1] and filled_list is None.


RE: Newbie lists problem - buran - Dec-13-2018

empty_list = []
first_var = 1

filled_list = empty_list.append(first_var) # here it will append to empty_list and append returns None which is assigned to filled_list
print(filled_list)
print(empty_list)
Output:
None [1] >>>
So your code is equivalent to
empty_list = []
first_var = 1
empty_list.append(first_var)
filled_list = None
print(filled_list)



RE: Newbie lists problem - LedDiode - Dec-16-2018

Okay, it's clearer to me now ! Thanks you both for helping newbies like me we appreciate that :D see you soon ^^'