Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Lists union and intersecion
#6
This is one way to do it
# convert to sets
result = set(dia).union(set(mots))
print(result)
print(list(result))
 
result2 = set(dia).intersection(set(mots))
print(result2)
print(list(result2))
However, this will not preserve order and set have unique elements, so if there are duplicates in the list (same element more than one time in list) they will be lost


And this is working with lists - order and repeating elements are preserved
# if order is imporatnt
result = [element for element in dia if element in set(mots)] # this is list comprehension, but it can be replaced by regular loop
print(result)
 
dia.extend(mots)
print(dia)
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Messages In This Thread
Lists union and intersecion - by arbiel - Mar-27-2020, 05:51 PM
RE: Lists union and intersecion - by buran - Mar-27-2020, 05:53 PM
RE: Lists union and intersecion - by arbiel - Mar-27-2020, 08:00 PM
RE: Lists union and intersecion - by buran - Mar-27-2020, 08:21 PM
RE: Lists union and intersecion - by arbiel - Mar-27-2020, 11:01 PM
RE: Lists union and intersecion - by buran - Mar-28-2020, 05:57 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Inheritance vs Union gserranowong 3 2,280 Jun-29-2021, 06:13 PM
Last Post: gserranowong
  ImportError: cannot import name 'Union' from '_ctypes' (unknown location) ciuffoly 15 10,486 Oct-09-2020, 06:58 AM
Last Post: ciuffoly
  Split dict of lists into smaller dicts of lists. pcs3rd 3 2,415 Sep-19-2020, 09:12 AM
Last Post: ibreeden
  sort lists of lists with multiple criteria: similar values need to be treated equal stillsen 2 3,311 Mar-20-2019, 08:01 PM
Last Post: stillsen
  Union of dictionaries (taking max value on collision) meee 5 3,795 Jan-17-2018, 09:14 PM
Last Post: Mekire

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020