In Python, when you use +
for concatenating two lists a new list is created and returned. This means that when you wrote x + y
, a new list is created. This also means that after x = x + y
, the local variable x
will now refer to the newly created list(as a result of x + y
). If you want to change the original list in-place you could instead use the extend
method as explained in the below example.
#--------v--v------------->x and y are local variables that refer to the passed objects
def func(x, y):
#-------vvvvv------------->this x + y creates a new list
x = x + y
#---^--------------------->the "local variable x" on the left hand side now refers to the new list object created as a result of x + y
return x
c = [5,4,6,4]
d = [6,7,8,9]
t = func(c,d) #here t refers to the object returned by the call to func which essentially was created from x + y
print(t) #prints the object return by the call to func [5, 4, 6, 4, 6, 7, 8, 9]
print(c) #prints c which still refers to the original list [5, 4, 6, 4]
Note instead of writing x = x + y
and then returning x
you could just have written return x + y
and the effect will be the same, as shown below:
#--------v--v------------->x and y are local variables that refer to the passed objects
def func(x, y):
return x +y #creates and returns a new list object
c = [5,4,6,4]
d = [6,7,8,9]
t = func(c,d) #here t refers to the object returned by the call to func which essentially was created from x + y
print(t) #prints the object return by the call to func [5, 4, 6, 4, 6, 7, 8, 9]
print(c) #prints c which still refers to the original list [5, 4, 6, 4]
If you want to change the original list in-place you can use list's extend
method as shown below:
#--------v--v------------->x and y are local variables that refer to the passed objects
def func(x, y):
#-----vvvvvv-------------->changes x in-place instead of creating a new list
x.extend(y);
c = [5,4,6,4]
d = [6,7,8,9]
#no need to do the assignment here because the changes made to the list inside func will be reflected in the original list as we have used extend method
func(c,d)
print(c) #prints c [5, 4, 6, 4, 6, 7, 8, 9]
Similarly, in C++ you're using the std::vector::insert
member function of std::vector
that will insert the elements into the vector on which the member function was called(which is the vector x
). And since you've passed the vector x
by reference, the change will be reflected in the original vector.