+ 9

How to find union of two lists?

I have two lists: A=[ "python" , "c" , "Java" , "perl" ] B=[ "php" , "JavaScript" , "python" , "SQL" , "Java" ] how can I get union of both lists?

26th May 2018, 12:02 PM
KUNTAL NAYAK
KUNTAL NAYAK - avatar
11 Réponses
+ 7
thanks Jan Markus and Mohit the coder (M.S.D) for this help.
26th May 2018, 12:18 PM
KUNTAL NAYAK
KUNTAL NAYAK - avatar
+ 3
Jan Markus yeah I read it wrong check now I updated my code for numbers
26th May 2018, 12:10 PM
MsJ
MsJ - avatar
+ 3
Also if you don’t want to turn the lists into sets, you can do: inter = [s for s in A if s in B] A_ = [s for s in A if s not in B] B_ = [s for s in B if s not in A] U = inter + A_ + B_
29th May 2018, 4:43 AM
Pedro Demingos
Pedro Demingos - avatar
+ 3
Ok newlist = list(set(list1) | set(list2)) i think this will work
29th May 2018, 5:39 PM
AISHWARYA KASTHALA
AISHWARYA KASTHALA - avatar
+ 2
AISHWARYA KASTHALA ya it will be fine. 😊 But I find it somehow useless to convert lists into sets before taking union as u have done. print ("newlist :", list1 l list2) will simply do the job.
29th May 2018, 5:53 PM
KUNTAL NAYAK
KUNTAL NAYAK - avatar
+ 2
can u answer this: how to write a menu based program to insert,sort and reverse a list of items
29th May 2018, 6:18 PM
AISHWARYA KASTHALA
AISHWARYA KASTHALA - avatar
+ 1
You can create a function def union(list1,list2): newlist = list1+ list2 return newlist list1 = ['python','c','java','perl'] list2 = ['php','javascript','python','sql','java,] print(union(list1,list2))
29th May 2018, 5:23 PM
AISHWARYA KASTHALA
AISHWARYA KASTHALA - avatar
+ 1
AISHWARYA KASTHALA but in your output 'java' and 'python' will repeat ... which is not allowed when we r taking union of two lists.
29th May 2018, 5:31 PM
KUNTAL NAYAK
KUNTAL NAYAK - avatar
+ 1
AISHWARYA KASTHALA I am also a beginner though .. not having enough knowledge of sorting, inserting stuffs. I suggest u to post it in your wall .. some expert will surely answer it.
29th May 2018, 6:25 PM
KUNTAL NAYAK
KUNTAL NAYAK - avatar
0
I like Python
30th May 2018, 8:32 AM
Aakash Kumar
Aakash Kumar - avatar