I'm trying to add 2 to the elements of a list without changing the elements of the original list in python. I used the append method, but when I try to return the original is modified too. It should work like this:
>> list1 = [1, 3, 5]
>> add_two(list1)
[3, 5, 7]
>> list1 == [1, 3, 5]
True
However this is what I got:
>> list1 = [1, 3, 5]
>> add_two(list1)
[3, 5, 7]
>> list1
[3, 5, 7]
Can anyone help me please?
List is a mutable data type. If you want to manipulate it without changing the original, you should pass the copy of that list to the function add_two().
In [1]: def add_two(lst):
...: lst[2] += 2
...: return lst
...:
In [2]: a = [ 1,2,3]
In [3]: add_two(a)
Out[3]: [1, 2, 5]
In [4]: a
Out[4]: [1, 2, 5]
In [5]: add_two(a.copy())
Out[5]: [1, 2, 7]
In [6]: a
Out[6]: [1, 2, 5]
EDIT
I see you want to increase each list element by two. Then it is easiest to use list comprehension - creates a new list, no need to pass a copy...
def add_two(lst):
return [v+2 for v in lst]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.