0

I'm getting started with Python and currently learning about list comprehensions so this may sound really strange.

Question: Is it possible to use list comprehension to create a list of elements in t and s without duplicates? Sort of like union of two sets but using lists instead...?

I use basic python so I'm not allowed use any shortcut 'reserved' words...

Jérôme Radix
  • 10,285
  • 4
  • 34
  • 40
tom
  • 3
  • 2

2 Answers2

2

In fact, you're trying to do an union of two sets. Use set/frozenset datatype to do this, not list comprehension :

>>> t = ['a', 'b', 'c']
>>> s = ['b', 'd', 'e']
>>> u = set(t)
>>> v = set(s)
>>> u
set(['a', 'c', 'b'])
>>> v
set(['b', 'e', 'd'])
>>> u | v
set(['a', 'c', 'b', 'e', 'd'])
>>> u.union(v)
set(['a', 'c', 'b', 'e', 'd'])
>>> u.union(s)                
set(['a', 'c', 'b', 'e', 'd'])

See this SO answer for more information.

Community
  • 1
  • 1
Jérôme Radix
  • 10,285
  • 4
  • 34
  • 40
1

Yes, it's possible to "union" two lists:

>>> s = [1,2,3,4]
>>> t = [3,5,4,7]
>>> 
>>> s + [x for x in t if x not in s]
[1, 2, 3, 4, 5, 7]

However, this is bad Python, because the comprehension part will scan the whole list s for each element in t. In real code, you should use sets, as @Jérôme showed.

georg
  • 211,518
  • 52
  • 313
  • 390