Home > database >  python set comprehension for loop unexpected return
python set comprehension for loop unexpected return

Time:08-05

i'm trying to do an excercise from pynative. I did it using for loop and using the set method difference_update. Now i want to do the for loop using comprehension but i don't get it right, the set returns empty The last one is the one giving me hard times. The expected output should be {10, 30} but it returns {None}

Update the first set with items that don’t exist in the second set Given two Python sets, write a Python program to update the first set with items that exist only in the first set and not in the second set.

set1 = {10, 20, 30}
set2 = {20, 40, 50}
for i in set2:
    if i in set1:
        set1.remove(i)
print(set1)

set11 = {10, 20, 30}
set21 = {20, 40, 50}
set11.difference_update(set21)
print(set11)

THIS IS THE ONE
set12 = {10, 20, 30}
set22 = {20, 40, 50}
set12 = {set12.remove(x) for x in set22 if x in set12}
print(set12)

CodePudding user response:

in the below line of code :

set12 = {set12.remove(x) for x in set22 if x in set12}

you first modify the set12 and remove extra element then replace set 12.

use this code in the last line

setppp = {set12.remove(x) for x in set22 if x in set12}
print(set12)
  • Related