Set of Data Structures in Python

Set

Definition

  • One of the data structure in python.
  • Create set of data

Data Structures in Python

  1. List:
  2. Tuple: ( )
  3. Dictionary: { key : value }
  4. set: { }

declaration

  • use { and } to declare

setA={1,3,4,"test"} # {1, 'test', 3, 4}
setB={2,4,"test",5,6} # {2, 'test', 4, 5, 6}

Characteristics

  • No duplicated value
  • Do not care about order
  • set algebra(union, intersection, difference, symmetric difference)

Set Algebra

union

Keyword: “|”, “union()”

union example


setA={1,3,4,"test"} # {1, 'test', 3, 4}
setB={2,4,"test",5,6} # {2, 'test', 4, 5, 6}


print(setA|setB)
print(setA.union(setB))
# {1, 2, 3, 4, 5, 6, 'test'}

intersection

Keyword: “&",“intersection()”

intersection example


setA={1,3,4,"test"} # {1, 'test', 3, 4}
setB={2,4,"test",5,6} # {2, 'test', 4, 5, 6}

print(setA&setB)
print(setA.intersection(setB))
# {'test', 4}

difference of sets

Keyword: “-",“difference()”

difference of sets example


setA={1,3,4,"test"} # {1, 'test', 3, 4}
setB={2,4,"test",5,6} # {2, 'test', 4, 5, 6}

print(setA-setB)
print(setA.difference(setB))
# {1, 3}

symmetric difference

Keyword: “^”,“symmetric_difference()”

symmetric difference example


setA={1,3,4,"test"} # {1, 'test', 3, 4}
setB={2,4,"test",5,6} # {2, 'test', 4, 5, 6}

print(setA^setB)
print(setA.symmetric_difference(setB))
# {1, 2, 3, 5, 6}

 Share!

 
comments powered by Disqus