Explanation:
๐น Line 1: Create the First Set
{1, 2, 3}
Python creates a set containing:
1
2
3
Memory:
Set A
{1, 2, 3}
๐น Line 2: Create the Second Set
{2, 3, 4}
Python creates another set containing:
2
3
4
Memory:
Set B
{2, 3, 4}
๐น Line 3: Apply the & Operator
{1, 2, 3} & {2, 3, 4}
The & operator means:
Find the intersection of both sets.
Intersection means:
Return only the elements that are present in both sets.
๐น Step 1: Compare Element 1
Python checks:
Is 1 present in Set B?
Set B:
{2, 3, 4}
Answer:
No
So 1 is not included.
๐น Step 2: Compare Element 2
Python checks:
Is 2 present in Set B?
Answer:
Yes
So Python keeps:
2
๐น Step 3: Compare Element 3
Python checks:
Is 3 present in Set B?
Answer:
Yes
So Python keeps:
3
๐น Step 4: Ignore Element 4
4 exists only in the second set.
Since intersection keeps common elements only, 4 is not included.
๐น Result After Intersection
Common elements are:
{2, 3}
Python creates a new set containing these elements.
๐น Line 4: Print the Result
print({2, 3})
Output:
{2, 3}
⚡ Visual Representation
Set A
{1, 2, 3}
Set B
{2, 3, 4}
Common elements:
Set A Set B
{1 2 3} {2 3 4}
▲ ▲
│
Common Elements
Result:
{2, 3}
๐ฅ Understanding Set Operators
Intersection (&)
{1,2,3} & {2,3,4}
Output:
{2,3}
(Common elements)
Union (|)
{1,2,3} | {2,3,4}
Output:
{1,2,3,4}
(All unique elements)
Difference (-)
{1,2,3} - {2,3,4}
Output:
{1}
(Elements only in the first set)
Symmetric Difference (^)
{1,2,3} ^ {2,3,4}
Output:
{1,4}
(Elements present in exactly one of the sets)
❌ Common Mistake
Many developers think:
&
means AND like in Boolean logic.
For sets, it has a different meaning.
It means:
Intersection
That is:
Keep only the elements that appear in both sets.
๐ฏ Final Result
{2, 3}
✅ Correct Output
{2, 3}

0 Comments:
Post a Comment