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
            Asked
            
        
        
            Active
            
        
            Viewed 49 times
        
    0
            
            
         
    
    
        oliinykmd
        
- 81
- 2
- 4
- 
                    2Why would python make 6 copies of those lists? – roganjosh Aug 30 '18 at 11:10
- 
                    1A "copy" of the list would be the entire list. If the list contains 6 items, why would you make 6 copies of the entire list? – roganjosh Aug 30 '18 at 11:12
- 
                    Do you mean 6 elements inside that list? – Karan Dhir Aug 30 '18 at 11:14
- 
                    No, how exactly Python make two lists concatenation with + operator. When we talk about itertools.chain it uses generator, but with + what is the exact mechanism? – oliinykmd Aug 30 '18 at 11:43
3 Answers
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