If you add the same line to two different lists or collections in Python, are you using twice as much memory?

For example, if you add the same line to the dict and list?

+3
source share
4 answers

A copy of the line does not fit in both, they just point to one line.

+4
source

Strings are immutable and are never copied. Indeed, even if you manually request a copy, you will still get the same object:

>>> import copy
>>> s = "abc"
>>> t = copy.copy(s)
>>> u = copy.deepcopy(s)
>>> id(s), id(t), id(u)
(139730866789424, 139730866789424, 139730866789424)
>>> s is t, s is u
(True, True)
+3
source

, ( ). , , , , , , .

, (Python 2.6 - , ):

>>> def f1(s, d, l):
...   d['z'] = s
...   l.append(s)
... 
>>> d={}
>>> l=[]
>>> f1('ciao', d, l)
>>> d['z'] is l[0]
True
>>> def f1(s, d, l):
...   d['z'] = s + 'zap'
...   l.append(s + 'zap')
... 
>>> f1('ciao', d, l)
>>> d['z'] is l[1]
False
>>> d['z'] == l[1]
True
>>> 

- - . - - , , , , , Python , .

+3

. :

s = "Some string."

, , dict :

d = {"akey": s}
l = [s]

d["akey"] l[0] , s, " ".

0

Source: https://habr.com/ru/post/1752027/