Create a list
#Create an empty list
my_list = []
my_list = [0, 1, 2, 3, 4, 5]
#An list of one byte (with a value of 17):
my_list = [17]
#A list of 5 elements each with a value of None
my_list = [None] * 5
#A list of 5 elements each with a value of 0
my_list = [0] * 5
#Alternative way to create a list 5 entries long containing 0
my_list = [0 for i in range(5)]
Multiple data types
A list can contain different data types
MyArray = ["Dave", 13, 46, True, 0.3]
Adding to a list
my_array.append(0x12)
Accessing list elements
for index in xrange(0, 24):
led_values[index] = 0]
Multi dimension lists
See here
Access list items
print(MyArray[2])
#You can also access in reverse in python by using negative indexes
print(MyArray[-1]) #Will print the last item in the list
print(MyArray[-2]) #Will print the second to last item in the list
Get a slice of list items
MyNewArray = MyArray[2:6] #New array has items from index 2 to 5 (2nd parameter is 1 more than that wanted)
MyNewArray = MyArray[:3] #New array has first 3 items from index
MyNewArray = MyArray[-2:] #New array has last 2 items from index
Manipulate lists
Add list items
MyArray.append('Hi') #Add to end
MyArray.insert(0, 'Hi') #Insert at index 0
Joins 2 lists / concatenate
MyArray = [10, 13, 46, 28]
MyArrayNew = MyArray + [13, 22]
Remove list item
#Remove at index
MyArray.pop(2) #Remove the list item at index 2
Item = MyArray.pop() #Remove the list item at the last index and assign its value to the variable Item
#Remove item with value
MyArray.remove('Hi') #Remove the first list item that matches the string specified (will error if not present)
Length
Length = len(MyArray)
Sort List
You can sort values and also strings alphabetically
#Sort an array
MyArray.sort() #Just this (no need for MyArray= )
MyArray.sort(reverse=True) #Sort in reverse order
#Copy an array and then sort it
MyNewArray = sorted(MyArray)
How many times does value occur in a list
NumOfTimes = MyArray.count('Hi')
Feel free to comment if you can add help to this page or point out issues and solutions you have found. I do not provide support on this site, if you need help with a problem head over to stack overflow.