Python Language Set: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
Line 47: Line 47:




=<tt>frozenset</tt>=
=<tt>frozenset()</tt>=
 
The <code>fronzenset()</code> returns an immutable frozenset object initialized with the elements from a given iterable. frozenset objects can be used as dictionary keys.
 
If the iterable contains duplicate elements, they are ignored (the iterable is handled like a set):
<syntaxhighlight lang='py'>
f = frozenset(['a', 'b', 'c'])
f2 = frozenset(['a', 'b', 'c', 'a'])
assert f == f2
</syntaxhighlight>

Revision as of 18:49, 11 September 2022

Internal

TODO

Overview

Sets and the __hash__() Function

Sets and the __hash__() Function

Initialization

Literal initialization:

s = {1, 2, 3}

Set from a tuple:

s = set((1, 2, 3))

Set from a list:

s = set([1, 2, 3])

Set from a string:

s = set('ABC')
print(s)  # {'C', 'B', 'A'}

Shallow Copy

s = set()
s.add('a')
s2 = s.copy()

Remove an Element from a Set

s.remove('a')

Does not return anything.

Convert to List

s=set()
l=list(s)


frozenset()

The fronzenset() returns an immutable frozenset object initialized with the elements from a given iterable. frozenset objects can be used as dictionary keys.

If the iterable contains duplicate elements, they are ignored (the iterable is handled like a set):

f = frozenset(['a', 'b', 'c'])
f2 = frozenset(['a', 'b', 'c', 'a'])
assert f == f2