Set
Similar to Python sets, the sets in Python Parser contain unique and unordered items and support the same operations.
Creating a Set
A set can be created using curly braces {} or the set
function. Note
that you cannot use set comprehension to create a set in Python Parser.
-
Method 1: Creating a set using curly braces {}.
// method 1: curly braces {} st = {1,2,"3","4","5"} type(st)
Output: set
-
Method 2: Creating a set using the
set
function.// method 2: set([iterable]) st1 = set(['e', 'o', 'g', 'l']) type(st1)
Output: set
Accessing Set Items
Set items cannot be accessed directly by referring to an index as they are unordered.
Updating a Set
-
Adding immutable set items
st.add("0") st
Output: {1, 2, '3', '4', '5', '0'}
st.add([1,3,5])
Output: 'TypeError: unhashable type: 'list''
-
Updating a set by adding items from another set
st.update({'0', 1, 2, '4', '5', '6'}) st
Output: {1, 2, '3', '4', '5', '0', '6'}
-
Removing set items
-
remove()
: Remove the specified item from a set. If the specified item does not exist in the set,remove()
will raise an error.st.remove('3') st
Output: {1, 2, '4', '5', '0', '6'}
st.remove('7')
Output: 'KeyError: "7"'
-
discard()
: Remove the specified item from a set. Different fromremove()
,discard()
will not raise an error if the specified item does not exist in the set.st = {1,2,"3","4","5"} st.discard('4') st
Output: {1, 2, '3', '5'}
st.discard('4') // Remove item '4' again. No error is raised though '4' does not exist. st
Output: {1, 2, '3', '5'}
-
pop()
: Remove a random item from a set and return the removed item.st = {1,2,"3","4","5"} st.pop()
Output: 1
-
clear()
: Empty a set.st = {1,2,"3","4","5"} st.clear() st
Output: {}
-
Getting Available Attributes and Methods of a Set
dir(st)
Output: ['__bitAnd__', '__bitOr__', '__bitXor__', '__dir__', '__eq__', '__ge__', '__gt__', '__ibitAnd__', '__ibitOr__', '__ibitXor__', '__init__', '__isub__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__repr__', '__req__', '__rne__', '__str__', '__sub__', 'add', 'clear', 'copy', 'difference', 'difference_update', 'discard', 'intersection', 'intersection_update', 'isdisjoint', 'issubset', 'issuperset', 'pop', 'remove', 'symmetric_difference', 'symmetric_difference_update', 'toddb', 'union', 'update']
toddb
is a unique method in Python Parser, which supports converting
a Python Parser set into a DolphinDB set. As DolphinDB set is strongly typed, the
conversion through toddb
fails if the types of items in a Python
Parser set are not consistent.
st = {1,2,"3","4","5"}
type(st.toddb())
Output: TypeError: keyType can't be BOOL or ANY
st = {1, 2, 3, 4, 5}
type(st.toddb())
Output: dolphindb.SET.INT