0

I have a question in the following code in python: why doesn't it give the same result when creating the list by comprehension and the list in a normal way?

lista = ['hola', 'mundo', 'hola', 13, 14]

#LISTA POR COMPRENSIÓN
lista1 = []
lista1 = [ (i, lista.count(i)) for i in lista if ((i, lista.count(i)) not in lista1)]
print('Lista: ', lista1)

#LISTA DE FORMA NORMAL
lista2 = []
for x in lista:
    if(x, lista.count(x)) not in lista2:
        lista2.append( (x, lista.count(x)) )
print('Lista: ', lista2)
Henry Ecker
  • 34,399
  • 18
  • 41
  • 57
  • Consider what happens if you don't assign anything to `lista1` before the list comprehension. – shadowtalker Feb 28 '23 at 01:18
  • As @shadowtalker says, just delete `lista1=[]` that's the power of list comprehensions, you don't have to initialize the list. Also, think what should be instead of `not in lista1` if you don't initialize it. – eliasmaxil Feb 28 '23 at 01:26

0 Answers0