List
A list is a collection which is ordered and changeable. In Python lists are written with square brackets. |
List Example
RYB_color = ["Red","Yellow","Blue"] print(RYB_color) >>>['Red','Yellow','Blue']
|
Access Items
RYB_color = ["Red","Yellow","Blue"]
|
print(RYB_color[1]) >>> 'Yellow'
|
print(RYB_color[-2]) >>> 'Yellow'
|
Range of Indexes
RYB_Secondary = ["Red","Yellow","Blue","Orange","Green","Purple"] Example 1 print(RYB_Secondary[1:5] >>>['Yellow','Blue','Orange','Green']
|
Note: Index 5 is not included. |
Example 2 print(RYB_Secondary[-5:-2] >>>['Yellow','Blue','Orange','Green']
|
Note: Index -2 is not included. |
Example 3 print(RYB_Secondary[:5] >>>['Red','Yellow','Blue','Orange','Green']
|
Note: By leaving out the start value, the range will start at the first item. |
Example 4 print(RYB_Secondary[1:] >>>['Yellow','Blue','Orange','Green','Purple']
|
Note: By leaving out the end value, the range will go on to the end of the list. |
|
|
List Length
RYB_color = ["Red","Yellow","Blue"] print(len(RYB_color)) >>> 3
|
Change Item Value
RYB_color = ["Red","Yellow","Blue"] RYB_color[1] = "Green" print(RYB_color) >>>['Red','Green','Blue']
|
Add Items
RYB_color = ["Red","Yellow","Blue"]
|
Using the append()
method to append an item in the and of the list. |
RYB_color.append("White") >>> ['Red','Yellow','Blue','White']
|
Use the insert()
method to add an item at the specified index. |
RYB_color.insert(2,"White") >>> ['Red','Yellow','White','Blue']
|
Delete Items
RYB_color = ["Red","Yellow","Blue"]
|
RYB_color.remove("Yellow")
|
#remove the item "Yellow"
|
|
#remove the indicated index or the last item if index not specified. In this case the item "Blue" will be removed
|
|
#remove the item "Yellow"
|
|
|
|
|
Check if Item Exists
RYB_color = ["Red","Yellow",Blue"] if "Yellow" in RYB_color: print("Yes")
|
|
Created By
Metadata
Favourited By
Comments
No comments yet. Add yours below!
Add a Comment
Related Cheat Sheets
More Cheat Sheets by Nouha_Thabet