Show Menu
Cheatography

Python Lists - Part II & Tuples Cheat Sheet by

Copy a List

RYB_color = ["Re­d","Y­ell­ow",­Blu­e"]

Example 1
 Copy_RYB = RYB_co­lor.copy()

Example 2
Copy_RYB = list(R­YB_­color)

Join Two Lists

RYB_color = ["Re­d","Y­ell­ow",­Blu­e"] 
Second­_color = ["Gr­een­"­,"Or­ang­e","P­urp­le"]

Example 1
RYB_Second = RYB_co­lor.ex­ten­d(S­eco­nd_­color)

Example 2
RYB_Second = RYB_color + Second­_color

The list() Constr­uctor

RYB_color = list((­"­Red­"­,"Ye­llo­w",B­lue­"))

Tuple

A tuple is a collection which is ordered and unchan­geable. In Python tuples are written with round brackets.

Tuple Example

RYB_color = ("Re­d","Y­ell­ow",­"­Blu­e") 
print(­RYB­_color)
>>>­('R­ed'­,'Y­ell­ow'­,'B­lue')

Access Tuple Items

Same as access list items. Please check "­Access list items" in "­Python Lists - Part I" cheat sheet.

Change Tuple Values

Since tuples are inchan­geable, then we cannot change any value. But, we can convert a tuple to a list, change the values that we want within the list and convert the list back into a tuple.
Example
`RYB_color = ("Re­d","Y­ell­ow",­"­Blu­e") 
L = list(R­YB_­color)
L[0] = "­Mag­ent­a"
RYB_color = tuple(X)
 

Check if Item Exists

Same as checking item witin a list . Please check "­Check if Item Exists­" in "­Python Lists - Part I" cheat sheet.

Tuple Length

Same as list length. Please check "List Length­" in "­Python Lists - Part I" cheat sheet.

Add Items

Once a tuple is created, we cannot add items to it. Tuples are unchan­geable.

Create Tuple With One Item

To create a tuple with only one item, we have add a comma after the item, unless Python will not recognize the variable as a tuple.
Color = ("Wh­ite­",)

Remove Items

Tuples are unchan­geable, so we cannot remove items from it, but we can delete the tuple comple­tely.
RYB_color = ("Re­d","Y­ell­ow",­"­Blu­e")  
del RYB_color

Join Two Tuples

RYB_color = ("Re­d","Y­ell­ow",­"­Blu­e") 
Second­_color = ("Or­ang­e","G­ree­n","P­urp­le")
RYB_Second = RYB_color + Second­_color

The tuple() Constr­uctor

RYB_color = tuple(­("Re­d","Y­ell­ow",­"­Blu­e"))
 

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