Tuples and sets

Tuple creation

Tuples are immutable sequences and cannot be added, deleted or modified

# use () to create tuple1 = (" t1 ", "t2", 10) print (tuple1) tuple1 = "t1", "t2", Print (tuple1) print(tuple2) = tuple(("t1", "t2", 30)) print(tuple2) print(type(tuple2)) # empty tuple4 = ("python",) print(tuple3) print(type(tuple3)) # empty tuple4 = () tuple5 = tuple() print(tuple4) print(type(tuple4)) print(tuple5) print(type(tuple5))Copy the code

Tuple elements are immutable

t = (10, [20, 30], 40) print(t, type(t)) print(t[0], type(t[0])) # 10 <class 'int'> print(t[1], type(t[1])) # [20, 30] <class 'list'> print(t[2], type(t[2])) # 40 <class 'int'> # Print (id(list1)) print(id(list1)) print(id(list1))Copy the code

Traversal of tuples

t = (10, 20, 30)
for i in t:
    print(i)
Copy the code

Collection creation

The elements in the set are not repeated and are unordered

set1 = {1, "Python", 2, 3, 4, 3, 2} print(set1) # {1, 2, 3, 4, 'Python'}; The elements in the set are not repeated, Print (set2) set2 = set(range(6)) print(set2) set2 = set([1, 3, 5, 7]) print(set2) set2 = set((7, 5, 3) 1)) print(set2) set2 = set("python") print(set2) # {'y', 'o', 't', 'h', 'p', 'n'}; Set2 = set({7, 5, 3, 10}) print(set2) set2 = set() print(set2) # set(); Empty collectionCopy the code

Operation of set

Print (10 in set1) print(10 not in set1) print(10 not in set1) print(10 not in set1) Update ([70, 80, 100]) print(set1) # {80, print(set1) # {80, 50, 20, 100, 70, 40, 10, 30} set1 = {10, 20, 30, 40, 50} set1.update({70, 80, 101}) print(set1) set1 = {10, 20, 30, 40, Print (1) print(2) # {1, 2} print(2) # {1, 3} print(3) # {2, 3} print(3) # {2, 4} print(4) # {3, 4} 40, 30} set1 = {10, 20, 30, 40, 50} # set1.remove(100) # KeyError: 100; Set1 = {10, 20, 30, 40, 50} set1.pop() print(set1) # {20, 40, 10, 30}; Set1 = {10, 20, 30, 40, 50} set1.clear() print(set1) # set() : Set1 = {10, 20, 30, 40, 50} for I in set1: print(I)Copy the code

Relation of sets

# Equal judgment, S1 = {10, 20, 30, 40} s2 = {40, 20, 30, 10} print(s1 == s2) # True Subset (s1) = {0, 0, 0} subset(s1) = {0, 0, 0} subset(s1) = {0, 0, 0} subset(s1) = {0, 0, 0} 40} s2 = {10, 20, 30} s3 = {10, 20, 60} print(s1.issuperset(s2)) # True print(s1.issuperset(s3)) # False 300} s3 = {10, 20, 60} print(s1.isdisjoint(s2)) # True; Return True print(s1.isdisJoint (s3)) # False;Copy the code

Mathematical operations on sets

S1 = {10, 20, 30, 40} s2 = {10, 20, 50, 60} # print(s1. Intersection (s2)) # {10, } print(s1. Union (s2) print(s1. Union (s2)) # {40, 10, 50, 20, 60, 30} print (s1 | s2) # take difference set print (s1) difference (s2)) # {40, Print (s1. Symmetric_difference (s2)) # {40, 50, 60, 30} print(s1 ^ s2)Copy the code

Set generator

s1 = {i * 2 for i in range(6)}
print(s1)  # {0, 2, 4, 6, 8, 10}
Copy the code