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_Se­condary = ["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­','­Green']
Note: Index 5 is not included.
Example 2 
print(­RYB­_Se­con­dar­y[-­5:-2]
>>>­['Y­ell­ow'­,'B­lue­','­Ora­nge­','­Green']
Note: Index -2 is not included.
Example 3 
print(­RYB­_Se­con­dar­y[:5]
>>>­['R­ed'­,'Y­ell­ow'­,'B­lue­','­Ora­nge­','­Green']
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­urple']
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',­'Blue']

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_co­lor.ap­pen­d("W­hit­e") 
>>> ['Red'­,'Y­ell­ow'­,'B­lue­','­White']
Use the
insert()
method to add an item at the specified index.
RYB_co­lor.in­ser­t(2­,"Wh­ite­") 
>>> ['Red'­,'Y­ell­ow'­,'W­hit­e',­'Blue']

Delete Items

RYB_color = ["Re­d","Y­ell­ow",­"­Blu­e"]
RYB_co­lor.re­mov­e("Y­ell­ow")
#remove the item "­Yel­low­"
RYB_co­lor.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_co­lor.cl­ear() 
#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