Monday, 12 January 2026

Python Coding Challenge - Question with Answer (ID -130126)

 


Let’s explain it step-by-step:

s = {1, 2, 3} s.add([4, 5])
print(s)

 What happens here?

Line 1

s = {1, 2, 3}

A set is created with three integers.


Line 2

s.add([4, 5])

Here you are trying to add a list [4, 5] into a set.

๐Ÿ‘‰ But sets can only store hashable (immutable) objects.

  • int, float, str, tuple → hashable ✅

  • list, dict, set → not hashable

A list is mutable, so Python does not allow it inside a set.

So this line raises an error:

TypeError: unhashable type: 'list'

Line 3

print(s)

This line is never executed, because the program stops at the error in line 2.


Final Output

There is no output — instead you get:

TypeError: unhashable type: 'list'

✅ How to fix it?

If you want to store 4 and 5 as a group inside the set, use a tuple:

s = {1, 2, 3} s.add((4, 5))
print(s)

Output (order may vary):

{1, 2, 3, (4, 5)}

Or if you want to add them as individual elements:

s = {1, 2, 3} s.update([4, 5])
print(s)

Output:

{1, 2, 3, 4, 5}

๐Ÿ”‘ Key Concept

Sets only allow immutable (hashable) elements.
That’s why lists can’t go inside sets — but tuples can 

900 Days Python Coding Challenges with Explanation 

0 Comments:

Post a Comment

Popular Posts

Categories

100 Python Programs for Beginner (118) AI (179) Android (25) AngularJS (1) Api (7) Assembly Language (2) aws (27) Azure (8) BI (10) Books (261) Bootcamp (1) C (78) C# (12) C++ (83) Course (84) Coursera (299) Cybersecurity (28) Data Analysis (24) Data Analytics (16) data management (15) Data Science (241) Data Strucures (15) Deep Learning (97) Django (16) Downloads (3) edx (21) Engineering (15) Euron (30) Events (7) Excel (18) Finance (9) flask (3) flutter (1) FPL (17) Generative AI (51) Git (9) Google (47) Hadoop (3) HTML Quiz (1) HTML&CSS (48) IBM (41) IoT (3) IS (25) Java (99) Leet Code (4) Machine Learning (217) Meta (24) MICHIGAN (5) microsoft (9) Nvidia (8) Pandas (12) PHP (20) Projects (32) Python (1238) Python Coding Challenge (960) Python Mistakes (27) Python Quiz (392) Python Tips (5) Questions (3) R (72) React (7) Scripting (3) security (4) Selenium Webdriver (4) Software (19) SQL (45) Udemy (17) UX Research (1) web application (11) Web development (8) web scraping (3)

Followers

Python Coding for Kids ( Free Demo for Everyone)