Appending to List Eror

Question:

I’m new to Python and am struggling with the syntax to join a new value to a list and then add that to a list of lists. loc_ref and from_loc are both pre-existing lists and user_says is a user input field using user_says = input("Enter Data")

print(loc_ref,"n")  #returns [['COMPANY|ADDRESS|CITY|STATE|LOCATION']] 
print(from_loc,"n") #returns ['COMPANY A', '1515 STREET RD', 'CITYA', 'ST'] 
print([user_says])
loc_ref = loc_ref.append(from_loc + [user_says]) 
print(loc_ref)  #returns None 

Why is loc_ref returning None ?

Asked By: Emily Alden

||

Answers:

That is because the method append returns None. Sounds weird? That’s because it works in-place and changes the list loc_ref, but will always return None.

All you have to do is simply change your line to:

loc_ref.append(from_loc + [user_says])

The original list will simply have the appended value in it, at the last position.

Read more about it here:

The append() method adds a single item to the existing list. It doesn’t return a new list; rather it modifies the original list.

Answered By: Tomerikoo

You’re setting the value of loc_ref to None

loc_ref = loc_ref.append(from_loc + [user_says])

list.append does not return the list with the appended value, it returns None, as a result, loc_ref is set to None

Try just:
loc_ref.append(from_loc + [user_says]) and get rid of the loc_ref =

Answered By: isstiaung

https://www.programiz.com/python-programming/methods/list/append

As mentioned, the append() method only modifies the original list. It doesn’t return any value.

append() is a method that doesn’t return anything just doing loc_ref.append(from_loc + [user_says]) will be enough

Answered By: Jvol Jvolizka
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.