Skip to content Skip to sidebar Skip to footer

Assign Value Of A List Into Another List While Using Append Or Insert Method Returning None As Output

I am a beginner in python. I am trying to assign value of a list into another list while using append or insert method. However, the output is always none. Can you please advise. B

Solution 1:

 guest_list = ['AA', 'BB', 'CC', 'DD'] 
 guest_list.append("XX") 
 print(guest_list)

 guest_list = ['AA', 'BB', 'CC', 'DD'] 
 guest_list.insert(0,"XX") 
 print(guest_list)

What you can do is first append the data to the list and then print the list itself as append does not return anything hence you are getting None as an output.If you want to assign this list to another variable then you can do this after appending data.

new_list=guest_list
print(new_list)

Solution 2:

That's not how append() works. The function adds the item to guest_list but returns nothing (None) so when you're setting new_guest_list = guest_list.append('XX') the interpreter is essentially doing the following:

1.) Add the item 'XX' to guest_list
2.) Set new_guest_list to None

If your guest_list is mutable (i.e you want it to be updated), just guest_list.append('XX') will suffice and it'll be updated. If however you want your guest_list immutable (i.e. keep it unchanged for the record), you will want to:

1.) Optional: Set your guest_list as a tuple object (note the use of regular bracket instead of square bracket), this way it will prevent accidental changes as tuple objects are immutable:

guest_list = ('AA', 'BB', 'CC', 'DD')

2.) Set your new list as a copy of your guest_list:

new_guest_list = list(guest_list)

3.) Append your new item to new list:

new_guest_list.append('XX')

The values of your guest_list and new_guest_list will be as follow:

guest_list: ('AA', 'BB', 'CC', 'DD')
new_guest_list: ['AA', 'BB', 'CC', 'DD', 'XX']

Post a Comment for "Assign Value Of A List Into Another List While Using Append Or Insert Method Returning None As Output"