ListA list is a collection which is ordered and changeable. In Python lists are written with square brackets. |
List ExampleRYB_color = ["Red","Yellow","Blue"] print(RYB_color) >>>['Red','Yellow','Blue']
|
Access ItemsRYB_color = ["Red","Yellow","Blue"]
| print(RYB_color[1]) >>> 'Yellow'
| print(RYB_color[-2]) >>> 'Yellow'
|
Range of IndexesRYB_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 LengthRYB_color = ["Red","Yellow","Blue"] print(len(RYB_color)) >>> 3
|
Change Item ValueRYB_color = ["Red","Yellow","Blue"] RYB_color[1] = "Green" print(RYB_color) >>>['Red','Green','Blue']
|
Add ItemsRYB_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 ItemsRYB_color = ["Red","Yellow","Blue"]
| RYB_color.remove("Yellow")
| #remove the item "Yellow"
| RYB_color.pop()
| #remove the indicated index or the last item if index not specified. In this case the item "Blue" will be removed
| del RYB_color[1]
| #remove the item "Yellow"
| del RYB_color
| #delete the whole list
| RYB_color.clear()
| #return an empty list
|
Check if Item ExistsRYB_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