Python Forum

Full Version: Newbie lists problem
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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
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.
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 :)
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.
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)
Okay, it's clearer to me now ! Thanks you both for helping newbies like me we appreciate that :D see you soon ^^'