First of all, sorry if this questions is extremely basic, I'm just starting with Python.
I'm having problems understanding how Python 3.6 creates and appends objects to lists. See the following code:
a_dict=dict()
a_list=list()
for i in range(100):
a_dict['original'] = i
a_dict['multi'] = i*2
a_list.append(a_dict)
The print of the list goes like
print(a_list)
>>[{'original': 99, 'multi': 198}{'original': 99, 'multi': 198}...{'original': 99, 'multi': 198}]
According to my original thoughts, i=0 -> original=0, multi=0; i=1 -> original=1, multi=2; etc...
But, according to this question here, Python's append() appends a pointer to the object not the actual value. So I change the append(original) on my original code to append(copy):
a_dict=dict()
a_list=list()
for i in range(100):
a_dict['original'] = i
a_dict['multi'] = i*2
a_list.append(a_dict.copy()) ##change here
Now, I get the desired result:
print(a_list)
[{'original': 0, 'multi': 0}, {'original': 1, 'multi': 2}, {'original': 2, 'multi': 4},...]
Now, here is my question:
How append() really works? Do always lists contain pointers-like objects to their originals? How about other types? Should I always use copy() if my intentions are not to directly mess with the original values or the list/container I'm using?
Hope I'm explaining myself good enough. And again sorry if it's a basic question. Thanks.
💡 Tips: When you use . append() the original list is modified. The method does not create a copy of the list – it mutates the original list in memory.
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.
The + operator creates a new list in python when 2 lists are combined using it, the original object is not modified. On the other hand, using methods like extend and append, we add the lists in place, ie, the original object is modified.
Bookmark this question. Show activity on this post. The first element of the list is overwritten.
This has to do with mutability of the objects you append. If the objects are mutable, they can be updated, and you essentially add a reference to your list with the .append()
function. Thus in these situations you need a copy.
A pretty good list of which types are mutable and not is found on this site. However, generally, container types tend to be mutable whereas simple values typically are immutable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With