Python Lists - Part I Cheat Sheet

A Programming › Python cheat sheet in English by Nouha_Thabet
12,021 views 2,529 downloads 7 Dec 2019 History
4.9 avg · 1 rating

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)
>>>­['Re­d','Y­ell­ow',­'­Blu­e']

Access Items

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

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]
>>>­['Ye­llo­w','B­lue­'­,'Or­ang­e','G­ree­n']
Note: Index 5 is not included.
Example 2
print(­RYB­_Se­con­dar­y[-­5:-2]
>>>­['Ye­llo­w','B­lue­'­,'Or­ang­e','G­ree­n']
Note: Index -2 is not included.
Example 3
print(­RYB­_Se­con­dar­y[:5]
>>>­['Re­d','Y­ell­ow',­'­Blu­e','O­ran­ge',­'­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:]
>>>­['Ye­llo­w','B­lue­'­,'Or­ang­e','G­ree­n','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)
>>>­['Re­d','G­ree­n','B­lue­']

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")
>>> ['Re­d','Y­ell­ow',­'­Blu­e','W­hit­e']
Use the insert() method to add an item at the specified index.
RYB_co­lor.in­ser­t(2­,"Wh­ite­")
>>> ['Re­d','Y­ell­ow',­'­Whi­te',­'­Blu­e']

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.

Cheatography n. The art of mapping complex subjects into clear, instantly navigable reference guides.