0

What I have as input:

list: [[2, 4], [2, 6], [2, 8]]

What I want as output:

set: 2,4,6,8

What I'm currently doing(not working):

def convert(input_list):
    all_nums = set([arr[0], arr[1]] for arr in input_list)
    return all_nums

I know I can manually iterate through parent array and add contents of child array to the set like this:

def convert(input_list):
    all_nums = set()
    for inner_list in input_list:
        all_nums.add(inner_list[0])
        all_nums.add(inner_list[1])
    return all_nums
  • How to do do that in pythonic way?
  • In second approach can I do something like all_nums.add(inner_list[0], inner_list[1])?
noobie
  • 751
  • 4
  • 13
  • 33

5 Answers5

6

Simply:

my_list = [[2, 4], [2, 6], [2, 8]]
my_set = {e for l in my_list for e in l}

This is using a "set comprehension", which is a squashed down version of:

my_list = [[2, 4], [2, 6], [2, 8]]
my_set = set()
for l in my_list:
    for e in l:
        my_set.add(e)

Alternatively, you could do:

my_list = [[2, 4], [2, 6], [2, 8]]
my_set = set()
for l in my_list:
    my_set.update(l)

(Variable names shamelessly stolen from modesitt.)

wizzwizz4
  • 6,140
  • 2
  • 26
  • 62
  • In second approach can I do something like all_nums.add(inner_list[0], inner_list[1])? – noobie Aug 10 '18 at 15:45
  • You need double brackets so you're adding a tuple (immutable, hashable list), but yes. Alternatively, you could do `my_set = {(l[0], l[1]) for l in my_list}` or `my_set = {tuple(l) for l in my_list}` or `my_set = {(x, y) for x, y in my_list}`. – wizzwizz4 Aug 10 '18 at 15:48
  • in second approach doing `all_nums.add((inner_list[0], inner_list[1]))` gives `{(2, 8), (2, 6), (2, 4)}` but **not** {2, 4, 6, 8} – noobie Aug 10 '18 at 16:07
  • I thought that was what you wanted... – wizzwizz4 Aug 10 '18 at 16:18
  • is there a way I can get {2, 4, 6, 8} without adding them separately inside for-loop (see the second approach)? – noobie Aug 10 '18 at 16:21
  • @noobie Use `my_set.update(inner_list)`. – wizzwizz4 Aug 10 '18 at 16:22
2

One approach using itertools.chain and set

Ex:

from itertools import chain
l = [[1, 2], [1, 3], [1, 4]]
print(set(chain.from_iterable(l)))

Output:

set([1, 2, 3, 4])
  • chain to flatten the list
Rakesh
  • 81,458
  • 17
  • 76
  • 113
1

You can try this:

from itertools import chain

l = [[1, 2], [1, 3], [1, 4]]
l = list(chain.from_iterable(l))
set_l = set(l)
brandonwang
  • 1,603
  • 10
  • 17
0

I would do the following

set_ = {e for l in my_list for e in l}
modesitt
  • 7,052
  • 2
  • 34
  • 64
0

You can use set comprehension:

l = [[2, 4], [2, 6], [2, 8]]
print({i for s in l for i in s})

This outputs:

{8, 2, 4, 6}
blhsing
  • 91,368
  • 6
  • 71
  • 106