0

I have read a lot info here and here but I still don't understand is python really make 6 copies of lists when, for example it concatenate [1,2,3,4] + [5,6] these 2 lists

oliinykmd
  • 81
  • 2
  • 4

3 Answers3

1

Python doesn't make 6 copies of the list, rather it joins or concatenates the two lists and makes them into one i.e [1,2,3,4,5,6].

List concatenation in Python: How to concatenate two lists in Python?.

Karan Dhir
  • 731
  • 1
  • 6
  • 24
0

No, only the references are copied. The objects themselves aren't copied at all. See this:

class Ref:
   ''' dummy class to show references '''
   def __init__(self, ref):
       self.ref = ref
   def __repr__(self):
      return f'Ref({self.ref!r})'

x = [Ref(i) for i in [1,2,3,4]]
y = [Ref(i) for i in [5,6]]

print(x)   # [Ref(1), Ref(2), Ref(3), Ref(4)]
print(y)   # [Ref(5), Ref(6)]

z = x + y
print(z)   # [Ref(1), Ref(2), Ref(3), Ref(4), Ref(5), Ref(6)]

# edit single reference in place
x[0].ref = 100
y[1].ref = 200

# concatenated list has changed
print(z)  # Ref(100), Ref(2), Ref(3), Ref(4), Ref(5), Ref(200)]
FHTMitchell
  • 11,793
  • 2
  • 35
  • 47
0

Let say there n number of list l1, l2, l3, ... and If you add them it has only one copy on some address.

eg:

In [8]: l1 = [1,2,3]
In [9]: l2 = [4,5,6]

In [10]: id(l1 + l2)
Out[10]: 140311052048072

In [11]: id(l1)
Out[11]: 140311052046704

In [12]: id(l2)
Out[12]: 140311052047136

id() returns identity of an object. https://docs.python.org/2/library/functions.html#id

P.Madhukar
  • 454
  • 3
  • 12