I want to do something like this:
myList = [10, 20, 30] yourList = myList.append(40)
Unfortunately, list append does not return the modified list.
So, how can I allow append
to return the new list?
The usual append method adds the new element in the original sequence and does not return any value.
A Python function can return any object such as a list. To return a list, first create the list object within the function body, assign it to a variable your_list , and return it to the caller of the function using the keyword operation “ return your_list “.
The append() function in Python takes a single item as an input parameter and adds it to the end of the given list. In Python, append() doesn't return a new list of items; in fact, it returns no value at all. It just modifies the original list by adding the item to the end of the list.
Don't use append but concatenation instead:
yourList = myList + [40]
This returns a new list; myList
will not be affected. If you need to have myList
affected as well either use .append()
anyway, then assign yourList
separately from (a copy of) myList
.
In python 3 you may create new list by unpacking old one and adding new element:
a = [1,2,3] b = [*a,4] # b = [1,2,3,4]
when you do:
myList + [40]
You actually have 3 lists.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With