Python lists when I pop in one does pop in the other for no apparent reason? [duplicate]

0

I put an example of what is happening to me, I equal an empty list with a list full of elements, and when I pop in one it does pop in the other but I need that when it is empty the second one is filled with the first one

lista1 = ['elemento1','elemento1','elemento1','elemento1','elemento1','elemento1']
lista2 = []

for i in range(0,50):
  if not lista2: lista2=lista1
  lista2.pop(0)
  print('lista1:',lista1)
  print('lista2:',lista2)

the result of this code is:

Python 3.6.1 (default, Dec 2015, 13:05:11)
[GCC 4.8.2] on linux

lista1: ['elemento1', 'elemento1', 'elemento1', 'elemento1', 'elemento1']
lista2: ['elemento1', 'elemento1', 'elemento1', 'elemento1', 'elemento1']
lista1: ['elemento1', 'elemento1', 'elemento1', 'elemento1']
lista2: ['elemento1', 'elemento1', 'elemento1', 'elemento1']
lista1: ['elemento1', 'elemento1', 'elemento1']
lista2: ['elemento1', 'elemento1', 'elemento1']
lista1: ['elemento1', 'elemento1']
lista2: ['elemento1', 'elemento1']
lista1: ['elemento1']
lista2: ['elemento1']
lista1: []
lista2: []
Traceback (most recent call last):
  File "python", line 6, in <module>
IndexError: pop from empty list
    
asked by Anthony 15.07.2018 в 19:01
source

1 answer

0

The error is that you are making a list2 = list1, try this way

for elem in lista1:
    lista2.append(elem)
    
answered by 15.07.2018 / 19:03
source