Reputation:
Consider this list here:
example=[]
And another:
python=["hi","bye","hello","yes","no"]
If I decide to add one of the elements from python to example, will a duplicate of that element b created or will the variable python lose an element.
example+=[python[0]]
So would the string "hi" be duplicated or transferred to example using the aforementioned example
Upvotes: 0
Views: 178
Reputation: 20794
A Python list stores only references to the elements. The elements (here the strings) are stored as outside objects.
Any Python assignment only copies a reference value. This way, the list is implemented as a dynamic array that stores references.
If you insert a string to a list, the source string object is not copied, only the reference to the same object is copied. The source element (here python[0]
) is not removed from the list python
when used on the right side of the assignment. It is only read and left untouched.
Upvotes: 0
Reputation: 27812
The string "hi" will be split into chars and assigned to example
when you do example+=python[0]
So example
in this case will contain ['h','i']
.
Also, the list python
will not lose an element.
Upvotes: 2
Reputation: 49866
No, there will be no "transfer". This is easy enough to check, by just printing the values after the operation.
Instead, the list example will have appended to it the elements of the first string:
>>> f = []
>>> f+= ["hi", "there"][0]
>>> f
['h', 'i']
This happens because a += b
is conceptually* equivalent to a = a+b
, and a+b
creates a list which has all the elements of a
followed by the elements of b
. A string is sequence, the elements of which are strings composed of individual characters, which is why you get this behaviour.
*
There are differences, notably that list + nonlist
won't work.
Upvotes: 1
Reputation: 168766
So would the string "hi" be duplicated or transferred?
No, the string "hi"
will neither be duplicated nor transferred. Rather, the length of the object to which example
is bound will increase by one, and the reference example[0]
will be bound to whatever object python[0]
was bound to. Additionally, neither the reference python
nor the object to which it is bound will be modified.
Note also, that your question has an error in the example. Where you actually said,
example += python[0]
You surely meant t say:
example += [python[0]]
Upvotes: 0
Reputation: 2075
You have to do the following example.append(python[0] That will take the 'hi' and copy to example
Upvotes: -2