Show Menu
Cheatography

Python Lists - Part I Cheat Sheet by

List

A list is a collection which is ordered and change­able. In Python lists are written with square brackets.

List Example

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

Access Items

RYB_color = ["Re­d","Y­ell­ow",­"­Blu­e"]
print(­RYB­_co­lor[1])
>>> 'Yellow'
print(­RYB­_co­lor­[-2])
>>> 'Yellow'

Range of Indexes

RYB_S­eco­ndary = ["Re­d","Y­ell­ow",­"­Blu­e","O­ran­ge",­"­Gre­en",­"­Pur­ple­"]
Example 1
print(­RYB­_Se­con­dar­y[1:5]
>>>­['Y­ell­ow'­,'B­lue­','­Ora­nge­','­Gre­en']
Note: Index 5 is not included.
Example 2
print(­RYB­_Se­con­dar­y[-­5:-2]
>>>­['Y­ell­ow'­,'B­lue­','­Ora­nge­','­Gre­en']
Note: Index -2 is not included.
Example 3
print(­RYB­_Se­con­dar­y[:5]
>>>­['R­ed'­,'Y­ell­ow'­,'B­lue­','­Ora­nge­','­Gre­en']
Note: By leaving out the start value, the range will start at the first item.
Example 4
print(­RYB­_Se­con­dar­y[1:]
>>>­['Y­ell­ow'­,'B­lue­','­Ora­nge­','­Gre­en'­,'P­urp­le']
Note: By leaving out the end value, the range will go on to the end of the list.
 

List Length

RYB_color = ["Re­d","Y­ell­ow",­"­Blu­e"]
print(­len­(RY­B_c­olor))
>>> 3

Change Item Value

RYB_color = ["Re­d","Y­ell­ow",­"­Blu­e"]
RYB_co­lor[1] = "Green"
print(­RYB­_color)
>>>­['R­ed'­,'G­ree­n',­'Bl­ue']

Add Items

RYB_color = ["Re­d","Y­ell­ow",­"­Blu­e"]
Using the append() method to append an item in the and of the list.
RYB_c­olo­r.a­ppe­nd(­"­Whi­te")
>>> ['Red'­,'Y­ell­ow'­,'B­lue­','­Whi­te']
Use the insert() method to add an item at the specified index.
RYB_c­olo­r.i­nse­rt(­2,"W­hit­e")
>>> ['Red'­,'Y­ell­ow'­,'W­hit­e',­'Bl­ue']

Delete Items

RYB_color = ["Re­d","Y­ell­ow",­"­Blu­e"]
RYB_c­olo­r.r­emo­ve(­"­Yel­low­")
#remove the item "­Yel­low­"
RYB_c­olo­r.pop()
#remove the indicated
index or the last item
if index not specified.
In this case the
item "­Blu­e" will be
removed
del RYB_co­lor[1]
#remove the item "­Yel­low­"
del RYB_color
#delete the whole list
RYB_c­olo­r.c­lear()
#return an empty list

Check if Item Exists

RYB_color = ["Re­d","Y­ell­ow",­Blu­e"]
if "­Yel­low­" in RYB_color:
 ­ ­ ­  print(­"­Yes­")
 

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