mycpen

Mycpen

记录学习历程与受益知识
github
telegram
bilibili

03_Python-CSDN_Data Types 2

Container Types

4 built-in data structures (container types)
    List: list => [val1, val2, val3, val4]
    Tuple: tuple => (val1, val2, val3, val4)
    Dictionary: dict => {key1: val1, key2: val2}
    Set: set => {key1, key2, key3, key4}

I. List (list)#

A list is a data structure for handling a group of ordered items.
Lists are the most flexible ordered collection object type in Python.
Lists can contain any type of object: strings, numbers, or even other lists.
Lists are mutable data types, meaning their values can be modified.
Example: represents a shopping list
    goods = ['milk', 'sneakers', 'coffee', 'phone', 'lamb', 'grapes', 'oranges']

Lists are defined by items separated by commas within square brackets.
# Example
# Define an empty list
>>> lst = []
>>> type(lst)
<class 'list'>
>>> lst2 = list()        # Note: factory function
>>> type(lst2)
<class 'list'>
# Lists can hold any object in Python:
>>> lst3 = list("abc")        # Note: string
>>> lst3 
['a', 'b', 'c']
>>> lst = [1, 'abc', 2.5, True]
>>> lst = [1, 'abc', 2.5, True, lst3]    # Note: other lists
>>> lst
[1, 'abc', 2.5, True, ['a', 'b', 'c']]

Basic Operations on Lists#

Indexing#

You can access elements in a list by their index, starting from 0, to retrieve an element.

# Example
>>> lst = [1, 2, 3]
>>> id(lst)
140078683813384
>>> lst += [4]
>>> id(lst)
140078683813384    # Note: memory address remains unchanged
>>> lst[0]
1
>>> lst[0] = "a"    # Note: changing the value of an element in the list
>>> id(lst)
140078683813384
# Index cannot be out of bounds (Index Error: list index out of range)
>>> lst
['b', 2, 3, 4]
>>> lst[4]        # Note: index out of bounds will raise an error
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range

Slicing#

Slicing is accessing elements in a list by index, allowing you to retrieve a sublist.
Start and end range: [start, end)
Step: default => 1
Start: default => when step is positive, start is 0; when step is negative, start is -1
End: default => when step is positive, end is the end of the list; when step is negative, end is the start of the list.
Note: all three values are optional.
# Example: positive slicing
>>> a = [1, 2, 3, 4, 5, 6]
>>> a[0:4]    # Note: slicing, the first 4
[1, 2, 3, 4]
>>> str = "123456"
>>> str[0:4]    # Note: slicing, the first 4
'1234'
>>> a[:4]        # Note: same effect
[1, 2, 3, 4]

# Example: negative slicing, step is -1
>>> a = [1, 2, 3, 4, 5, 6]
>>> a[-1:3:-1]    # Note: -1 points to 6, 3 points to 4, -1 goes from right to left
[6, 5]
>>> a[-1:-4:-1]    # Note: -1 points to 6, -4 points to 3, -1 goes from right to left
[6, 5, 4]
>>> a[-1:-44:-1]    # Note: -1 points to 6, -44 is out of bounds, -1 goes from right to left
[6, 5, 4, 3, 2, 1]
>>> a[-1:4:-1]    # Note: -1 points to 6, 4 points to 5, -1 goes from right to left
[6]
>>> a[-3:4:-1]    # Note: -3 points to 4, 4 points to 5, cannot get 5 from the left
[]                # Note: empty, when the starting position is incorrect, the result will be empty (no error)
Slice object (slice function)
The purpose of the slice function: to generate a slice object, which is equivalent to naming the content to be sliced.
# Example
>>> a = ["a", "b", "c", "d"]
>>> a
['a', 'b', 'c', 'd']
>>> b = [1, 2, 3, 4, 5, 6]
>>> s1 = slice(0, 3, 1)        # Note: need to pass parameters when referencing
>>> a[s1]                    # Note: slicing the first 3
['a', 'b', 'c']
>>> b[s1]                    # Note: slicing the first 3
[1, 2, 3]
>>> c = ["xx", "yy", "zz", "ee"]    
>>> c[s1]                    # Note: slicing the first 3
['xx', 'yy', 'zz']

Adding#

Ways to add elements to a list:
    append: adds to the end, as a whole, type is not limited
    insert: inserts an element at the index position
    extend: extends the list
# Example
# append
>>> a = ["apple", "orange", 123, 0.1111, "cali"]
>>> a.append("test")    # Note: appending a string
>>> a
['apple', 'orange', 123, 0.1111, 'cali', 'test']
>>> lst = ['a', 'b', 'c']
>>> lst2 = [1, 2, 3]
>>> lst.append(lst2)    # Note: the appended type is an array
>>> lst
['a', 'b', 'c', [1, 2, 3]]    # Note: the appended type is an array
# insert
>>> lst = ['a', 'b', 'c']
>>> lst.insert(1, 'd')        # Note: insert data before the 2nd element
>>> lst
['a', 'd', 'b', 'c']
# extend
>>> a = [1, 2, 3]
>>> str = "abc"
>>> a.extend(str)        # Note: extending a string
>>> a
[1, 2, 3, 'a', 'b', 'c']
extend and +
    Note: limited to types that can be converted to list (str, list, tuple)
# Example
>>> a = ['a', 'b', 'c']
>>> a2 = [1, 2, 3]
>>> a.extend(a2)
>>> a
['a', 'b', 'c', 1, 2, 3]
>>> a + ["5"]                # Note: + can only add list and list
['a', 'b', 'c', 1, 2, 3, '5']
>>> a
['a', 'b', 'c', 1, 2, 3]    # Note: + method does not change array a after execution
>>> b = a + ["5"]            # Note: can save changes by assigning to array b
>>> b                    # Note: can save changes by assigning to array b
['a', 'b', 'c', 1, 2, 3, '5']
>>> id(a)
140273972677768
>>> a += ["6"]
>>> id(a)
140273972677768    # Note: a += ["6"] memory address remains unchanged, object unchanged, content changed
>>> a = a + ["7"]
>>> id(a)
140273837551816    # Note: a = a + ["7"] memory address changes

Deleting#

Ways to delete elements from a list:
    pop: removes an element, defaults to the last one (specify index to remove)
    remove: removes the specified element (will raise an error if the data to be removed does not exist)
    del: removes by index
        del is a Python keyword used to delete variable (reference)
    clear: clears the list
# Example
# pop
>>> a.pop()    # Note: defaults to removing the last one
'7'            # Note: return value, the removed element
>>> a.pop(2)    # Note: specify index 2 to remove the 3rd element
'c'
# remove
>>> a = ["xx", "yy", "xx"]
>>> a.remove("xx")        # Note: removes the specified element, only removes the first one
>>> a
['yy', 'xx']
>>> a
['yy', 'xx']
>>> a.remove("zz")        # Note: will raise an error if the data to be removed does not exist
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: list.remove(x): x not in list
# del
>>> a = [1, 2, 3, "xx", "yy", "zz"]
>>> del a[3]        # Note: delete index 3 (the 4th element)
>>> a
[1, 2, 3, 'yy', 'zz']
>>> del a[0:2]    # Note: slice deletion
>>> c = 1
>>> del c            # Note: del deletes the variable reference
>>> c
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'c' is not defined
# clear
>>> a
[3, 'yy', 'zz']
>>> a.clear()
>>> a
[]            # Note: clear empties the list

Modifying#

Modifying elements mainly uses indexing and slicing to modify, add, or delete.

# Example
>>> a = [1, 2, 3, 'a', 'b', 'c']
>>> a
[1, 2, 3, 'a', 'b', 'c']
>>> a[2] = "x"    # Note: modifying an element
>>> a
[1, 2, 'x', 'a', 'b', 'c']
>>> a[1:1]        # Note: [1, 1)
[]                # Note: empty
>>> a[1:1] = "abc"    # Note: adding a list before the starting position with index 1
>>> a
[1, 'a', 'b', 'c', 2, 'x', 'a', 'b', 'c']
>>> b = ["a", "b", "c"]
>>> b[2:2] = ["x", "y"]        # Note: adding a list before index 2
>>> b
['a', 'b', 'x', 'y', 'c']
>>> b[2:4] = ["x", "y", "z"]    # Note: replacing values at indices 2 and 3
>>> b
['a', 'b', 'x', 'y', 'z', 'c']
>>> b[1:5] = "12"        # Note: after slicing, convert to list. str type converted to list
>>> b                # Note: replacing values at indices 1, 2, 3, 4 with '1', '2'
['a', '1', '2', 'c']
>>> b
['a', '1', '2', 'c']
>>> b[5:-3]            
[]
>>> b[3:-3]            # Note: cannot get
[]
>>> b[3:-3] = "xy"        # Note: replace with other list starting from this position
>>> b                # Note: check if the found element is empty
['a', '1', '2', 'x', 'y', 'c']
>>> c = ["a", "b", "c", "d", "1"]
>>> c[1:4] = "hello"    # Note: find b, c, d and replace bcd with h, e, l, l, o
>>> c
['a', 'h', 'e', 'l', 'l', 'o', '1']
>>> c = ['a', 'h', 'e', 'l', 'l', 'o', '1']
>>> c[5:3]                # Note: cannot get
[]
>>> c[5:3] = ["x", "y"]        # Note: c[5:3] is empty, insert x, y at o (index 5)
>>> c
['a', 'h', 'e', 'l', 'l', 'x', 'y', 'o', '1']

Reversing#

You can reverse a list using reverse or slicing.

# Example
# 1. Negative slicing to achieve reversal, output values are reversed
>>> a = [1, 2, 3, 4]
>>> a[::-1]            # Note: negative slicing
[4, 3, 2, 1]
>>> a                # Note: a's own value remains unchanged
[1, 2, 3, 4]
# 2. reverse method to reverse the list
>>> a
[1, 2, 3, 4]
>>> a.reverse()
>>> a        # Note: a's own value is reversed
[4, 3, 2, 1]

Sorting#

You can sort a list using sort.

# Example
>>> a
[4, 3, 2, 1]
>>> a.sort()
>>> a
[1, 2, 3, 4]            # Note: after sorting, a's own value changes
# Reverse sorting
a.sort(reverse=True)
>>> a
[1, 2, 3, 4]
>>> a.sort(reverse=True)    # Note: reverse sorting, ascending becomes descending
>>> a
[4, 3, 2, 1]                # Note: sorted from largest to smallest
# Sorting does not support mixing int and str:
>>> a = ["a", 1, "b", 2]
>>> a.sort()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: '<' not supported between instances of 'str' and 'int'
>>> a = ["a", "1", "b", "2"]
>>> a.sort()
>>> a
['1', '2', 'a', 'b']
# Sort by encoding
>>> a = ["a", "1", "b", "2", "A"]
>>> a
['a', '1', 'b', '2', 'A']

Counting#

You can use len, count, and index.

# Example
# len total length
>>> a
['a', '中', '序', '排', '文']
>>> len(a)
5
>>> a.append([1, 2, 3])
>>> len(a)
6
>>> a
['a', '中', '序', '排', '文', [1, 2, 3]]
>>> a.extend([1, 2, 3])
>>> len(a)
9
# count counts the number of occurrences of an element
>>> a
['a', '中', '序', '排', '文', [1, 2, 3], 1, 2, 3]
>>> a.count("a")
1
>>> a.count(1)
1
# index returns the index position of an element
>>> a = ["x", "y", "x", 1]
>>> a.count("x")
2
>>> a.index("x")
0
>>> a.index("z")        # Note: index finds the index by element, will raise an error if not found
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: 'z' is not in list

Iterating#

You can iterate through each item in the object.

A list is an iterable object and can be directly traversed using for.

# 1. for i in a:
>>> a
['x', 'y', 'x', 1]
>>> for i in a:
...     print(f"item is --->{i}")
... 
item is --->x
item is --->y
item is --->x
item is --->1

# 2. enumerate() function  
# Feature: returns a tuple containing each index and value
# Note: using one i to iterate, what you get is a tuple
>>> for i in enumerate(a):
...     print(f"item is --->{i}")
... 
item is --->(0, 'x')
item is --->(1, 'y')
item is --->(2, 'x')
item is --->(3, 1)
# Using two temporary variables to get the returned tuple from enumerate(a)
>>> for i, j in enumerate(a):
...     print(f"{i}-->{j}")
... 
0-->x
1-->y
2-->x
3-->1

Membership Testing#

You can check if a certain data exists in the list.

# Example
>>> lst = ['a', 'b', 'c', 'd']
>>> print('a' in lst)
True
>>> print('x' in lst)
False
>>> s = 'a'
>>> print(s, 'is in' if s in lst else 'is not in', 'the list')
a is in the list

Type Conversion#

You can convert a string (str) to a list (list).

# Example
>>> str = 'abc 123'
>>> list(str)
['a', 'b', 'c', ' ', '1', '2', '3']

II. Tuple (tuple)#

A tuple is a data structure for handling a group of ordered items.
Tuples, like strings, are immutable, meaning you cannot modify a tuple.
Tuples can contain any type of object: strings, numbers, or even other lists.
Use case: gender selection, database query results.
Example: represents a shopping list
    goods = ('milk', 'sneakers', 'coffee', 'phone', 'lamb', 'grapes', 'oranges')
# Example
# Tuples are defined by items separated by commas within parentheses
>>> a = ()
>>> type(a)
<class 'tuple'>
>>> a = (1)            # Note: parentheses can also represent a set
>>> type(a)
<class 'int'>
# When there is only one element in a tuple, you need to add a comma after the element to distinguish whether the parentheses represent a set or a tuple
>>> a = (1,)            # Note: when there is only one element in a tuple, you need to add a comma (,) to indicate a tuple
>>> type(a)
<class 'tuple'>
>>> a = tuple()        # Note: define an empty tuple
>>> type(a)
<class 'tuple'>
>>> a
()
# Tuples can hold any object in Python
>>> a = ("a", 1, 1.2, True, print)
>>> a
('a', 1, 1.2, True, <built-in function print>)

Basic Operations on Tuples#

Indexing#

You can access elements in a tuple by their index, starting from 0, to retrieve an element.

# Example
>>> a = ("a", 1, 1.2, True, print)
>>> a[4]
<built-in function print>
>>> a[3]
True
# Index cannot be out of bounds, will raise an error if out of bounds
>>> a = ("a", 1, 1.2, True, print)
>>> a[5]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: tuple index out of range

Slicing#

Slicing is accessing elements in a tuple by index, allowing you to retrieve a subtuple.
Start and end range: [start, end)
Step: default => 1
Start: default => when step is positive, start is 0; when step is negative, start is -1
End: default => when step is positive, end is the end of the tuple; when step is negative, end is the start of the tuple.
Note: all three values are optional.
# Example
>>> a = ("a", 1, 1.2, True, print)
>>> a[1:3]
(1, 1.2)

Immutability#

# Example
>>> a
('a', 1, 1.2, True, <built-in function print>)
>>> a[0] = 1                    # Note: raises an error
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
>>> tu1 = (1, 2)
>>> tu2 = (3, 4)
>>> tu3 = tu1 + tu2
>>> tu3
(1, 2, 3, 4)

Counting#

# Example
>>> a = ('a', 'b', 'c')
>>> print(len(a))
3

Iterating#

# Example
>>> a = [1, 2, 3]
>>> for i in enumerate(a):
...     print(i)
... 
(0, 1)        # Note: return value is a tuple
(1, 2)
(2, 3)
>>> for i, j in enumerate(a):
...     print(f"{i}---{j}")        # Note: using two parameters to receive the return value
... 
0---1
1---2
2---3

Membership Testing#

# Example
>>> a = ("a", "b", "c")
>>> "a" in a
True
>>> "d" not in a
True

III. Dictionary (dict)#

A dictionary is a key-value mapping data structure in Python.
Dictionaries are unordered.
Dictionaries are mutable objects.
Keys must be unique, thus inherently deduplicated.
Example:
    singer = {key1: value, key2: value}
    singer = {"Li Shengjie": 'Deeply in Love', 'Zhang Shaohan': 'A Diao', 'Wang Feng': 'Ordinary Disco'}
Dictionary definition:
    The key of a dictionary must be a hashable object.
    In Python, all strings, numbers, tuples, booleans, and None are hashable objects.
    The value of a dictionary can be any value.
# Example
# Define an empty dictionary
# Method 1:
>>> a = {}        # Note: define an empty dictionary
# Method 2:
>>> b = dict()    # Note: define an empty dictionary, factory function
>>> type(a)
<class 'dict'>
>>> type(b)
<class 'dict'>

# Example
>>> c = [('root', '123456'), ('admin', 'admin')]
>>> d = dict(c)        # Note: convert list to dictionary, factory function
>>> d
{'root': '123456', 'admin': 'admin'}
>>> e = [1, 2, 3]
>>> e
[1, 2, 3]
>>> dict(e)            # Note: the object to be converted must have key-value mapping format
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: cannot convert dictionary update sequence element #0 to a sequence

Basic Operations on Dictionaries#

Accessing Values#

Usage 1: dicts[key] => raises KeyError if the key does not exist
Usage 2: dicts.get(key, default) => returns default value if the key does not exist
# Example
>>> a = {"a": 4, "b": 2}
>>> a['a'] = 3            # Note: modify the value of key="a"
>>> a
{'a': 3, 'b': 2}
>>> a['c'] = 4            # Note: add a key-value pair
>>> a
{'a': 3, 'b': 2, 'c': 4}
>>> a['c']            # Note: access value
4
>>> a['d']            # Note: raises an error if the key does not exist
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'd'
# Recommended to use get
>>> a
{'a': 3, 'b': 2, 'c': 4}
>>> a.get('d')        # Note: does not raise an error
>>> c = a.get('d')
>>> print(c)
None                    # Note: default value is not set

Adding/Modifying#

Usage: dicts[key] = value
    When the key does not exist, it indicates adding a key-value pair.
    When the key exists, it indicates modifying the corresponding value.
# Example: modifying
>>> a
{'a': 3, 'b': 2, 'c': 4}
>>> a['a'] = 5
>>> a
{'a': 5, 'b': 2, 'c': 4}
# Example: adding
>>> a['d'] = False
>>> a
{'a': 5, 'b': 2, 'c': 4, 'd': False}

Deleting#

Usage 1: dicts.pop(key)
Usage 2: dicts.popitem()
# Example: dicts.pop(key)
>>> a = {'a': 5, 'b': 2, 'c': 4, 'd': False}
>>> a.pop('a')        # Note: delete the element with key='a'
5                    # Note: pop has a return value
>>> c = a.pop('b')        # Note: get the return value
>>> c
2
>>> a
{'c': 4, 'd': False}
# Example: dicts.popitem()
# In Python 3, it removes the last one
>>> a = {"x": 1, "y": 2, "z": 3}
>>> a.popitem()
('z', 3)
>>> a.popitem()
('y', 2)
>>> a.popitem()
('x', 1)            

Merging#

Usage 1: dict1.update(dict2) => merges dict2 into dict1
Usage 2: dict(dict1, **dict2) => merges dict1 and dict2 to create a new dictionary
# Example: dict1.update(dict2)
>>> a = {"x": 1, "y": 3}
>>> b = {"q": 2, "w": 3}
>>> a.update(b)    # Note: a's built-in method
>>> a
{'x': 1, 'y': 3, 'q': 2, 'w': 3}
>>> b
{'q': 2, 'w': 3}
# Example: dict(dict1, **dict2)
>>> a = {"x": 1, "y": 3}
>>> b = {"q": 2, "w": 3}
>>> dict(a, **b)    # Note: factory function, returns a dictionary merging a and b
{'x': 1, 'y': 3, 'q': 2, 'w': 3}
>>> a    # Note: a itself does not change
{'x': 1, 'y': 3}
>>> dict()
{}
>>> c = dict(a, **b)
>>> c
{'x': 1, 'y': 3, 'q': 2, 'w': 3}

Membership Testing#

Usage:
    item in dicts
    item not in dicts
# Example
>>> a = {"x": 1, "y": 2, "z": 3}
>>> a
{'x': 1, 'y': 2, 'z': 3}
>>> 'x' in a        # Note: in defaults to comparing keys
True
>>> 2 in a
False
>>> 2 in a.values()        # Note: a.values() compares values
True

Iterating#

By default, it iterates over keys.

# Example
>>> a
{'x': 1, 'y': 2, 'z': 3}

# Iterate over keys
>>> for i in a:
...     print(i)
... 
x              # Note: iterating over keys
y
z

# Iterate over values
>>> for i in a.values():
...     print(i)
... 
1               # Note: iterating over values
2
3

# To get both key and value
# items returns tuples
# Method 1
>>> for i in a.items():
...     print(i)
... 
('x', 1)
('y', 2)
('z', 3)
# Method 2
>>> for i, j in a.items():    # Note: using two parameters to get the return values key, value
...     print(f"key is {i}, value is {j}")
... 
key is x, value is 1
key is y, value is 2
key is z, value is 3
# Method 3
>>> for i in a.items():
...     print(f"key is {i[0]}, value is {i[1]}")    # Note: index to get parameters
... 
key is x, value is 1
key is y, value is 2
key is z, value is 3

IV. Set (set)#

A set is an unordered, unique data collection.
A set is essentially a dictionary that only contains keys.
Purpose of sets:
    Deduplication: converting a list to a set automatically removes duplicates.
    Relationship testing: tests the relationships between two sets of data, such as intersection, difference, union, etc.
    Example:
        singer = {"Li Shengjie", 'Zhang Shaohan', 'Wang Feng'}
Set definition:
    A set is defined by curly braces, with elements separated by commas.
    Set elements must be hashable objects, just like dictionaries.
    The only difference between set and dict is that it does not store corresponding values.
# Example
# Define an empty set (2 ways)
>>> a = {1, 2, 3}    # Note: first way
>>> type(a)
<class 'set'>
>>> a = set()        # Note: second way
>>> a
set()
>>> type(a)
<class 'set'>

Basic Operations on Sets#

Adding#

Usage: s.add(item) => adds one item
Usage: s.update(someitems) => adds multiple items
# Example
>>> s = {1, 2, 3}
>>> s.add(4)
>>> s
{1, 2, 3, 4}
>>> s.update("str")    # Note: str is expanded one by one
>>> s
{1, 2, 3, 4, 't', 'r', 's'}
>>> s.update({"x": 1, "y": 2})    # Note: dictionary expands by key
>>> s
{1, 2, 3, 4, 'x', 't', 'y', 'r', 's'}

Removing#

Usage 1: s.remove(item) => removes one item (raises KeyError if item does not exist)
Usage 2: s.discard(item) => removes one item (does nothing if item does not exist)
# Example
# remove
>>> s
{1, 2, 3, 4, 'x', 't', 'y', 'r', 's'}
>>> s.remove('r')
>>> s
{1, 2, 3, 4, 'x', 't', 'y', 's'}
>>> s.remove('p')    # Note: "p" does not exist, raises an error
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'p'
# discard
>>> s
{1, 2, 3, 4, 'x', 't', 'y', 's'}
>>> s.discard('o')    # Note: does nothing if it does not exist
>>> s.discard('x')
>>> s
{1, 2, 3, 4, 't', 'y', 's'}
# pop
>>> a = {"a", "b", "c"}
>>> a.pop()
'c'
>>> a.pop()
'a'
>>> a.pop()
'b'

Set Operations#

Union: returns a new set containing every element from both sets
Intersection: returns a new set containing common elements from both sets
Difference: returns a new set containing elements in the first set but not in the second
Symmetric Difference: returns a new set containing elements in either set but not in both
# Example
# Create sets
>>> set('hello')
{'e', 'o', 'l', 'h'}

# Union
>>> s1 = {1, 2, 3}
>>> s2 = {2, 3, 4}
>>> s1 | s2
{1, 2, 3, 4}
>>> s1.union(s2)
{1, 2, 3, 4}

# Intersection
>>> s1 = {1, 2, 3}
>>> s2 = {2, 3, 4}
>>> s1 & s2
{2, 3}
>>> s1.intersection(s2)
{2, 3}

# Difference
>>> s1 = {1, 2, 3}
>>> s2 = {2, 3, 4}
>>> s1 - s2
{1}
# Note: elements in s1 that are not in s2
>>> s2 - s1
{4}

# Symmetric Difference
>>> s1 = {1, 2, 3}
>>> s2 = {2, 3, 4}
>>> s1 ^ s2
{1, 4}
# Note: parts excluding the intersection

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.