Reputation: 1
I am currently learning Python on codecademy and I came across this statement that says that lists are hashable (thus, they can be used as input for the update method when wanting to add multiple elements to a list):
The
.update()
method can add multiple elements.# Create a set to hold the song tags song_tags = {'country', 'folk', 'acoustic'} # Add more tags using a hashable object (such as a list of elements) other_tags = ['live', 'blues', 'acoustic'] song_tags.update(other_tags) print(song_tags)
But searching what a hashable object was, I found out that lists are not hashable, so now I am confused. Is this a mistake or are lists hashable in this particular situation?
Upvotes: 0
Views: 39
Reputation: 44848
Lists aren't hashable:
>>> hash([])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
>>> {["hello", "world"]}
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
So yes, Codeacademy is incorrect here. set.update
accepts any iterable as an argument:
>>> d = set(); d.update("hello"); d # string
{'h', 'l', 'o', 'e'}
>>> d = set(); d.update(['h', 'i']); d # list
{'h', 'i'}
>>> d = set(); d.update((h for h in "hello")); d # generator
{'h', 'l', 'o', 'e'}
The only thing that matters is that its elements be hashable, not the iterable itself.
Upvotes: 2