Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to allow list append() method to return the new list

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?

like image 653
Wilk Avatar asked Oct 15 '12 19:10

Wilk


People also ask

Does append return a new list?

The usual append method adds the new element in the original sequence and does not return any value.

How do you return a new list in Python?

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 “.

What is the use of append () function in 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.


2 Answers

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.

like image 65
Martijn Pieters Avatar answered Oct 04 '22 08:10

Martijn Pieters


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.

like image 36
Damian Paszkowski Avatar answered Oct 04 '22 10:10

Damian Paszkowski