Add integers to multiset

I am using multisets because I need something that is fast and efficient but doesn’t care about the order. However, I noticed that while you can append strings to multisets via “update”, you can’t with integers.

I.e. you can write:

from multiset import Multiset

le = Multiset()

But this gives an error:

from multiset import Multiset

le = Multiset()

Is there a way to add integers to multisets?

Presumably Multiset.update behaves similarly to set.update, which accepts an iterable [1] of elements to be added to the set.

If you want to add a single element, try le.add(1) (or le.update([1])).

The first exampe works with strings more-or-less by accident. In Python, strings are themselves iterables. Iterating over a string produces each character (technically, Unicode code point), as a single-character string. If you try running your first example with a multi-character string, you’d probably get a different result than you’d expect. This is what happens with a plain old set:

>>> s = set()
>>> s.update("abc")
>>> s
{'c', 'a', 'b'}  # NOT {'abc'}

  1. or multiple iterables ↩︎

1 Like

Thanks! It works now.