Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: list.extend without mutating original variable

Tags:

I am wondering whether there is a way in Python to use .extend, but not change the original list. I'd like the result to look something like this:

>> li = [1, 2, 3, 4]   >> li [1, 2, 3, 4]   >> li.extend([5, 6, 7]) [1, 2, 3, 4, 5, 6, 7]   >> li [1, 2, 3, 4]   

I tried to google this a few different ways, but I just couldn't find the correct words to describe this. Ruby has something like this where if you actually want to change the original list you'd do something like: li.extend!([5,6,7]) otherwise it would just give you the result without mutating the original. Does this same thing exist in Python?

Thanks!

like image 880
Parris Avatar asked Mar 18 '13 05:03

Parris


People also ask

What is the difference between append () and extend () methods of list?

append() adds a single element to the end of the list while . extend() can add multiple individual elements to the end of the list.

How append () and extend () are different with reference to list in Python?

Python append() method adds an element to a list, and the extend() method concatenates the first list with another list (or another iterable). When append() method adds its argument as a single element to the end of a list, the length of the list itself will increase by one.

Is Python list append in place?

append() will place new items in the available space. Lists are sequences that can hold different data types and Python objects, so you can use . append() to add any object to a given list. In this example, you first add an integer number, then a string, and finally a floating-point number.


1 Answers

The + operator in Python is overloaded to concatenate lists, so how about:

>>> li = [1, 2, 3, 4] >>> new_list = li + [5, 6, 7] >>> new_list [1, 2, 3, 4, 5, 6, 7] 
like image 141
Adam Obeng Avatar answered Dec 22 '22 04:12

Adam Obeng