List Comprehension for this case

3

How can I use list comprehension for this 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 the even numbers of lista and a .

['A', 2, 8, 10]

How can I do this with list comprehension ?

    
asked by anonymous 15.09.2016 / 16:56

2 answers

5

(as @stderr concurrently suggested), in this case the simplest is to concatenate (or + ) the "a" to the list in understanding

novalista = [a] + [num for num in lista if num%2 == 0] 
    
15.09.2016 / 18:08
3

To verify that the current iteration item is an integer , and an even number or equal a do:

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

See 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 is a list that has only numbers and you just want to add a , such as suggested by JJoão , concatenate the variable as a list:

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

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

    
15.09.2016 / 17:36