List Comprehension for this case

Asked

Viewed 297 times

3

How can I use comprehensilist on for that case:

>>> a = 'A'
>>> lista = [1, 2, 8, 5, 10]
>>> l = [a, num for num in lista if num%2 == 0]
  File "<stdin>", line 1
    l = [a, num for num in lista if num%2 == 0]
                  ^
SyntaxError: invalid syntax

As you can see this syntax is not possible. My idea was to create a new list only with even numbers of lista and with a.

['A', 2, 8, 10]

How can I do that with comprehensilist on?

  • But what do you mean? You want A stay in the first item of the list and then even numbers?

  • @Wallacemaxters, not exactly. The order doesn’t matter, I just want to add a on the list.

  • 1

    maybe something like: l = [a] + [num for num in lista if num%2 == 0] ?

  • @Jjoao gave the answer. Put as answer so I can mark.

2 answers

5


(as @stderr simultaneously suggested), in this case the simplest is to concatenate(ie +) the "a" to the list in comprehension

novalista = [a] + [num for num in lista if num%2 == 0] 

3

To check if the current iteration item is a whole, and an even or equal number a do:

l = [item for item in lista if type(item) is int and item % 2 == 0 or item == a]

Take an example:

lista = [1, 2, 8, 5, 10, 'A', 'b', 12]
a = 'A'

print([item for item in lista if type(item) is int and item % 2 == 0 or item == a])
# [2, 8, 10, 'A', 12]

Editing: If it’s a list that only has numbers and you just want to add a, as suggested by Jjoão, concatenate the variable as a list:

l = [item for item in lista if item % 2 == 0] + [a]

Beyond the module operator %, you can also use the bitwise and, for example: item & 1 == 0.

  • I’m beginning to understand. I think he wants to put the A first, as if it were a head.

  • @Wallacemaxters From what I understand he wants a new list with even numbers of lista and/or also the value of a.

  • @stderr in your example lista already contain the value of a and if so I would no longer need to add it. What I want is a new list with the even values of lista and also add the value of a. I could do that: l = [num for num in lista if num%2 == 0] and then add a with l.append(a). But I want to do it with just one line of code.

  • 1

    @Matheussaraiva Just add a on the list: l = [item for item in lista if item % 2 == 0] + [a]

  • Because they put it up there as a comment. Someone put it up as an answer so I can mark.

  • These operator overloads that python has still amazes me, rsrsrsrs.

  • @stderr, we had comments from Simltaneos.. (at the same time, I liked your answer +1 by is int)

Show 2 more comments

Browser other questions tagged

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