Show Menu
Cheatography

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­("Ye­llo­w" 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.

Add Items

RYB_c­olo­r.a­dd(­"­Whi­te")
print(­RYB­_color)
>>> "­Red­"­,"Wh­ite­"­,"Ye­llo­w","B­lue­"

Get the Length of a Set

print­(le­n(R­YB_­color))
>>> 3

Delete a set

del RYB_color
 

Remove Item

RYB_c­olo­r.r­emo­ve(­"­Yel­low­")
print(­RYB­_color)
>>> {'Red'­,'B­lue'}
If the item doesn't exist then remove() will raise an error.
RYB_c­olo­r.d­isc­ard­("Ye­llo­w")
print(­RYB­_color)
>>> {'Red'­,'B­lue'}
If the item doesn't exist then disca­rd() 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_c­olo­r.c­lear()
clear() returns an empty set.

Join Two Sets

Secon­d_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­urp­le'}
union() joins two sets into a new one and excludes any duplicate items.
RYB_c­olo­r.u­pda­te(­Sec­ond­_color)
print(­RYB­_color)
>>> {'Yell­ow'­,'O­ran­ge'­,'R­ed'­,'G­ree­n',­'Bl­ue'­,'P­urp­le'}
update() inserts the items in Secon­d_c­olor into RYB_c­olor and excludes any duplicate items.

Help Us Go Positive!

We offset our carbon usage with Ecologi. Click the link below to help us!

We offset our carbon footprint via Ecologi
 

Comments

No comments yet. Add yours below!

Add a Comment

Your Comment

Please enter your name.

    Please enter your email address

      Please enter your Comment.

          Related Cheat Sheets

            Python 3 Cheat Sheet by Finxter

          More Cheat Sheets by Nouha_Thabet