Parris
Parris

Reputation: 18408

Python: list.extend without mutating original variable

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!

Upvotes: 24

Views: 18588

Answers (3)

Chris
Chris

Reputation: 444

Try using eval to create a temporary alteration to a list, for instance:

li = [1, 2, 3, 4]

Then, you can use the eval for purposes of seeing what a 'temporary modification to the list' might look like:

print([i for i in eval('li + [5,6,7]')])
print(li)

Just a warning that if you did this for a large list modification, if I'm remembering correctly, the '+' operator used in this fashion for lists is not very efficient.

Upvotes: -2

Adam Obeng
Adam Obeng

Reputation: 1542

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]

Upvotes: 55

user1149862
user1149862

Reputation:

I know it's awkward but it works:

a = [1,2,3]
b = list(a)
b.extend([4,5])

Upvotes: 4

Related Questions