From a list, return even numbers in python

Asked

Viewed 4,651 times

-1

I am trying to return only the even numbers of a list1=[4,3,2,5,7,6]

for the return in a Lista2=[2,4,6]

I tried the recursive method with for but returns the error: Typeerror: Unsupported operand type(s) for %: 'list' and 'int'

lista1 = [4,3,2,5,7,6]
lista2 = []

for lista2 in lista1:
    if lista1 % 2 == 0:
        print(lista2)
  • How about lista2 = [ el for el in lista1 if el % 2 == 0 ] ?

  • 1

    By the way, your function has nothing recursive. And you made a nice mess with the variables

  • Thank you, Jefferson. By the way, when you say 'mess with variables' what do you mean? I appreciate immensely help, I am starting the studies in Python and any constructive criticism is welcome.

  • You declare lista2 as an empty list. Then use as an iteration variable in the loop for, but compares an operation with the variable lista1 within the loop. That confusion.

  • You’re confusing very basic concepts needed to structure a program. Answering the question in a way that you would understand would amount to a "class 0" - I think the recommendation is that you look for some Python tutorial for beginners in programming, and read until they teach about "variables", "lists"".

  • Show people, thanks for the tips!

Show 1 more comment

2 answers

1


Apart from agreeing with the confusion already expressed in the previous comments, a solution would be:

lista1 = [4, 3, 2, 5, 7, 6]
lista2 = []
for valor in lista1:
    if valor % 2 == 0:
        lista2.append(valor)

print(lista2)

the "value" in for is the temporary variable that saves items from the list1

for valor in lista1:

therefore, in the conditional if "value" has rest 0 in the division, it is added to Lista2 using the append function()

if valor % 2 == 0:
        lista2.append(valor)
  • thank mmtz, great explanation.

0

for the return in a Lista2=[2,4,6]

That is, in a list of ordered pairs, utilize filter for filter the pairs, and Sorted for order her.

lista1 = [4, 3, 2, 5, 7, 6]
lista2 = sorted(filter(lambda x: x % 2 == 0, lista1))
  • Show!! Vlw sbrubes. Excellent

Browser other questions tagged

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