0

I've copied one element of a list but the id is still the same.

t=['bancorp', 'bancorp','bancorp ba','bancorp ali', 'gas eu', 'gas', 'karl', 'bancorp','bancorp america','uni','gas for','gas tr']

n=t[2]

id(n)
124661664

id(t[2])
124661664

I´ve tried this but the ID is still the same:

n=cp.deepcopy(t[2])

How Can I copy the value but with different ID?

EDIT:

When I slice:n=t[2:3][0]. The id is different.

But when I slice: n=t[0:1][0]. The ID is the same. Why did it happen?

Bach
  • 6,145
  • 7
  • 36
  • 61
CreamStat
  • 2,155
  • 6
  • 27
  • 43

3 Answers3

3

In python, smaller strings are interned. This allows for efficient memory use since strings are immutable. In short, for small identical strings you will get the same id value.

As to why t[2:3][0] was not interned, and t[0:1][0] was, it looks like Cython does not intern strings with whitespace.

Community
  • 1
  • 1
C.B.
  • 8,096
  • 5
  • 20
  • 34
0

If you're really determined to create a separate copy of a string, you could do:

>>> s = 'foo'
>>> t = ''.join(s)
>>> s
'foo'
>>> t
'foo'
>>> id(s) == id(t)
False

However, as strings are immutable (i.e. can't be changed in-place) you don't really get any benefit from this. For example:

>>> a = list('foo')
>>> a
['f', 'o', 'o']
>>> b = a[:] # only a shallow copy
>>> id(a[0]) == id(b[0])
True # share the same object
>>> a[0] += 'l' # 'modify' one of them
>>> a
['fl', 'o', 'o'] # changes a
>>> b
['f', 'o', 'o'] # doesn't change b
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
-1

Craete a empty list and try to copy

t=['bancorp', 'bancorp','bancorp ba','bancorp ali', 'gas eu', 'gas', 'karl', 'bancorp','bancorp america','uni','gas for','gas tr']
n = []
n = t[2:3]

print id(n)

print id(t[2])
MONTYHS
  • 926
  • 1
  • 7
  • 30
  • 2
    Not very useful - here `n` is an empty list, which (although it does not have the same id as `t[2]`) isn't what the OP wants. `t[2:3]` would give a list with the single element `t[2]`, but `id(t[2:3][0]) == id(t[2])`. – jonrsharpe Apr 07 '14 at 14:54
  • Just `print n` and you will see what I mean. – jonrsharpe Apr 07 '14 at 14:57
  • Why it doesn't work when n=t[0:1][0] ? In that case, the ID is still the same! – CreamStat Apr 07 '14 at 15:03
  • @MONTYHS `id(n) != id(t[2])` simply because `['bancorp ba'] != 'bancorp ba'` Note that `id(n[0]) == id(t[2])`. – jonrsharpe Apr 07 '14 at 15:20