# Python Multiset

• Last Updated : 21 Feb, 2022

Multiset package is similar to the Python set but it allows elements to occur multiple times. Implementation can be based on dictionary elements( It internally uses a dict for storage) to their multiplicity in the multisets.

## Features of Python Multiset:

• An unordered collection of element
• Hashable just like in a set
• It supports the same methods as Python set
• It supports set operations like Union, intersection, and (symmetric)

## Installation:

To install this module type the below command in the terminal.

`pip install multiset`

### Example 1: Basic example of a multiset

Here we are going to create a new, empty Multiset object.

## Python3

 `from` `multiset ``import` `*`   `# print empty multiset` `print``(Multiset())`   `# print multiset from iterable` `print``(Multiset(``'abcde'``))`   `# print multiset from mapping` `print``(Multiset({``'a'``: ``4``, ``'b'``: ``2``, ``'c'``: ``3``, ``'d'``:``1``}))`

Output:

```{}
{a, b, c, d, e}
{a, a, a, a, b, b, c, c, c, d}```

### Example 2:  Combination with multiset and sets

Here we are going to give a combination of the set along with multisets. For this, we will use multiset addition(+) operation with set.

## Python3

 `# create set` `set1 ``=` `{``'apple'``, ``'ball'``, ``'apple'``} ` `print``(``"Our set is: "``, set1)`   `# combine multiset` `mltst ``=` `Multiset(``'bal'``) ``+` `set1` `print``(``"New multiset: "``,mltst)`

Output:

```Our set is:  {'ball', 'apple'}
New multiset:  {b, a, l, ball, apple}```

### Example 3: Changing values of multisets

Multisets are mutable so we can change the element using update() methods.

## Python3

 `mltst ``=` `Multiset(``'aab'``)`   `# update multiset` `mltst.update(``'a'``)` `print``(``"New added element: "``, mltst)`

Output:

`New added element:  {a, a, a, b}`

### Example 4: Combine value into multiset using a combine

We can combine the element using combine() methods.

## Python3

 `print``(mltst)` `mltst.combine(``"2"``)`

Output:

```{b, a, l, apple, ball}
{b, a, l, apple, ball, 2}```

### Example 5: Copy multisets

We can combine the multiset using copy() methods.

## Python3

 `new_mltst ``=` `mltst.copy()` `print``(``"Copied multiset"``,new_mltst)` `print``(``"Original "``,mltst)`

Output:

```Copied multiset {b, a, l, apple, ball}
Original  {b, a, l, apple, ball}```

## Python Multiset objects:

My Personal Notes arrow_drop_up
Recommended Articles
Page :