Cheatography

# Python Sets Cheat Sheet by Nouha_Thabet

### Set

 A set is a collection which is unordred and unindexed in a way that we cannot be sure in which order the items will appear.

### Set Example

 ``RYB_color = {"Re­d","Y­ell­ow",­"­Blu­e"} print(­RYB­_color) >>> {'Red'­,'Y­ell­ow'­,'B­lue'}``

### The set() Constr­uctor

 ``RYB_color = set(("R­ed",­"­Yel­low­"­,"Bl­ue"))``

### Access Items

 Example 1 ``for x in RYB_color:  ­ ­ ­  print(x) >>> Red >>> Yellow >>> Blue `` Example 2 ``print(­"­Yel­low­" in RYB_color) >>> True``

### Change Items

 Since a set is not orderer neither indexed, then we cannot acces to any item to change its value.

 ``RYB_co­lor.ad­d("W­hit­e") print(­RYB­_color) >>> "­Red­"­,"Wh­ite­"­,"Ye­llo­w","B­lue­"``

### Get the Length of a Set

 ``print(­len­(RY­B_c­olor)) >>> 3``

### Delete a set

 ``del RYB_color``

### Remove Item

 ``RYB_co­lor.re­mov­e("Y­ell­ow") print(­RYB­_color) >>> {'Red'­,'B­lue'}`` If the item doesn't exist then ``remove()`` will raise an error. ``RYB_co­lor.di­sca­rd(­"­Yel­low­") print(­RYB­_color) >>> {'Red'­,'B­lue'}`` If the item doesn't exist then ``discard()`` will raise an error. ``c = thisse­t.pop() print(c) print(­thi­sset) >>> Yellow {{nl}] >>> {'Red'­,'B­lue'}`` Since a set is not orderer neither indexed, then we cannot change acces to any item to change its value. ``RYB_co­lor.cl­ear()`` ``clear()`` returns an empty set.

### Join Two Sets

 ``Second­_color = {"Gr­een­"­,"Or­ang­e","P­urp­le"} Color = RYB_co­lor.un­ion­(Se­con­d_c­olor) print(­Color) >>> {'Yell­ow'­,'O­ran­ge'­,'R­ed'­,'G­ree­n',­'Bl­ue'­,'P­urple'}`` ``union()`` joins two sets into a new one and excludes any duplicate items. ``RYB_co­lor.up­dat­e(S­eco­nd_­color) print(­RYB­_color) >>> {'Yell­ow'­,'O­ran­ge'­,'R­ed'­,'G­ree­n',­'Bl­ue'­,'P­urple'}`` ``update()`` inserts the items in ``Second­_color`` into ``RYB_color`` and excludes any duplicate items.