Welcome, guest | Sign In | My Account | Store | Cart

Suppose you have multiple lists. You want to print all unique items from the list. Now, what you could do is merge the lists into one_big_list (e.g., a + b +c), and then iterate over each item in one_big_list, etc. The solution proposed here gets this done faster and in one line of code. How? By using a python set. A python set is a dictionary that contains only keys (and no values). And dictionary keys are, by definition, unique. Hence, duplicate items are weeded out automatically. Once you have the set, you can easily convert it back into a list. As easy as that!

Python, 6 lines
1
2
3
4
5
6
a = ['a', 'b', 'c', 'd']
b = ['c', 'x', 'g', 'h']
c = ['1', 'as', 'ci', 'v']
d = ['1', '2', '3', '4']

print list(set().union(a, b, c, d))
Created by Johannes S on Tue, 5 Apr 2016 (MIT)
Python recipes (4591)
Johannes S's recipes (1)

Required Modules

  • (none specified)

Other Information and Tasks