A list comprehension is, in some sense, a syntactic wrapper around a generator expression. In this case, I would explicitly use generator expressions, and chain them together with itertools.chain
. This approach has the advantage of creating one list object, not two temporary objects that are used to create the third, final object.
from itertools import chain
FirstList = [10, 20, 23, 11, 17]
SecondList = [13, 43, 24, 36, 12]
thirdList = list(chain((num for num in FirstList if num % 2 == 1),
(num for num in SecondList if num % 2 == 0)))
print(thirdlist)
You might also want to use filter
instead of a generator expression for readability.
thirdList = list(chain(filter(lambda x: x%2 == 1, FirstList),
filter(lambda x: x%2 == 0, SecondList))
or
def even(x):
return x % 2 == 0
def odd(x):
return x % 2 == 1
thirdList = list(chain(filter(even, FirstList), filter(odd, SecondList)))
])` with `thirdlist + [
– albert Jan 03 '21 at 14:31]` is doable. Doing this for the first list comprehension as well, would result in a single line like `result = [] + []`