AJ. AJ. - 4 months ago 5x
Python Question

Pythonic Way to Create Union of All Values Contained in Multiple Lists

Doing some XML processing in python. (Edit: I'm forced to use Python 2.4 for this project, boo!) I want to know what is the most Pythonic way to do this (create union of all values in multiple lists):

def getUniqueAttributeValues(xml_attribute_nodes):
# split attribute values by whitespace into lists
result_lists=list(item.getContent().split() for item in xml_attribute_nodes)

# find all unique values
for result_list in result_lists:
for result in result_list:
if result in unique_results:

return unique_results

sth sth

set.union does what you want:

>>> results_list = [[1,2,3], [1,2,4]]
>>> results_union = set().union(*results_list)
>>> print results_union
set([1, 2, 3, 4])

You can also do this with more than two lists.