Anas Elghafari
Anas Elghafari

Reputation: 1162

Python list comprehension: is there a way to do [func(x) for x in list1 or list2]

Or [func(x) for x in list1 and list2] (for some function func), without having to create a new list that happens to be the union or intersection of the two lists.

Upvotes: 0

Views: 1103

Answers (3)

Adam Smith
Adam Smith

Reputation: 54243

import itertools

[x for x in itertools.chain(list1,list2)]

Note that this will add duplicates, so it's neither a union nor an intersection. If you want a true union/intersection:

set.union(map(set, [list1,list2])) # cast to list if you need
# union
set.intersection(map(set, [list1,list2])) # cast to list if you need
# intersection

From your edit:

def func(x):
    pass
    # do something useful

for element in list1:
    if element in list2:
        func(element)
# Or, but less readably imo
# # for element in filter(lambda x: x in list2, list1):
# #     func(element)

Upvotes: 2

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799390

You want itertools.chain().

[... in itertools.chain(list1, list2)]

Upvotes: 1

user2555451
user2555451

Reputation:

You can use itertools.chain to join the two lists without creating a new one:

from itertools import chain
lst = [x for x in chain(list1, list2)]

Below is a demonstration:

>>> from itertools import chain
>>> list1 = [1, 2, 3]
>>> list2 = [4, 5, 6]
>>> [x for x in chain(list1, list2)]
[1, 2, 3, 4, 5, 6]
>>> list(chain(list1, list2))  # Equivalent
[1, 2, 3, 4, 5, 6]
>>>

Upvotes: 2

Related Questions