In this program, I wanted it to include in the final list the even numbers of the first list and the odd numbers of the second, why doesn’t this happen?(python)

Asked

Viewed 43 times

-2

*In the final list, numbers appear that were not supposed to be there,
for example 103, which is an odd number from the first list.

lista_1 = [10,24,50,103,30,12]                             
lista_2 = [13, 16, 39, 14, 107, 35]                         
for elementos in lista_1:                                 
  if elementos % 2 == 0:                                  
    lista_1.remove(elementos)                                
for unidades in lista_2:                                     
  if unidades % 2 != 0:                                      
    lista_2.remove(unidades)                                 
lista_final = lista_1 + lista_2                              
print(lista_final)                                           

The code resulted in
[24, 103, 12, 16, 14, 35]

  • 1

    If you want the even elements of lista_1, why are you using the remove to remove them from the list? I recommend you do the table test to describe your code and understand what you really did.

  • Do not remove items from a list in the same loop that iterates on it: https://answall.com/q/466768/112052

1 answer

0


What’s happening in your question is that you’re removing, precisely the elements you wish to display.

When you do...

for elementos in lista_1:                                 
  if elementos % 2 == 0:                                  
    lista_1.remove(elementos)

... in reality you are checking whether elementos % 2 == 0 is even and, if it is, you remove it from the list. So it never goes right. The correct would be you do not remove it.

One of the right ways to resolve this issue is:

lista_1 = [10, 24, 50, 103, 30, 12]
lista_2 = [13, 16, 39, 14, 107, 35]
lista_final = list()
for elementos in lista_1:
    if elementos % 2 == 0:
        lista_final.append(elementos)
for unidades in lista_2:
    if unidades % 2 != 0:
        lista_final.append(unidades)
lista_final.sort()
print(lista_final)
print()

Note that the algorithm checks whether elementos % 2 == 0 if it is even, and if it is lista_final. Then the algorithm checks if unidades % 2 != 0 if it is odd and, if it is, add also in the lista_final.

Then sorts the list and then displays the lista_final containing the even numbers of lista_1 and the odd numbers of lista_2.

  • Thanks bro, I know what my mistake was

Browser other questions tagged

You are not signed in. Login or sign up in order to post.