Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python basics why set() works but {} fails? [duplicate]

s = ["this", "that", "this"]

Why does set(s) work but {s} fails with

TypeError: unhashable type: 'list'
like image 348
Coddy Avatar asked May 01 '26 09:05

Coddy


1 Answers

It's because they mean different things. set(s) iterates s to create a set, whereas the literal syntax {s} just attempts to create a set containing the single element s.

>>> set("abc")
{'a', 'b', 'c'}
>>> {"abc"}
{'abc'}

Try {*s} instead for the equivalent of set(s).

like image 84
wim Avatar answered May 03 '26 23:05

wim