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

my_list = ["Dave", 13, 46, True, 0.3]

Adding to a list

my_list.append(0x12)

Accessing list elements

for index in xrange(0, 24):
    led_values[index] = 0]

Multi dimension lists

See here

Access list items

print(my_list[2])

#You can also access in reverse in python by using negative indexes
print(my_list[-1])    #Will print the last item in the list
print(my_list[-2])    #Will print the second to last item in the list
Get a slice of list items
MyNewArray = my_list[2:6]    #New array has items from index 2 to 5 (2nd parameter is 1 more than that wanted)


my_list_new = my_list[:3]     #New array has first 3 items from index
my_list_new = my_list[-2:]    #New array has last 2 items from index

Manipulate lists

Add list items
my_list.append('Hi')      #Add to end

my_list.insert(0, 'Hi')   #Insert at index 0
Joins 2 lists / concatenate
my_list = [10, 13, 46, 28]
my_list_new = my_list + [13, 22]
Remove list item
#Remove at index
my_list.pop(2)        #Remove the list item at index 2
Item = my_list.pop()  #Remove the list item at the last index and assign its value to the variable Item


#Remove item with value
my_list.remove('Hi')    #Remove the first list item that matches the string specified (will error if not present)

Length

Length = len(my_list)

Sort List

You can sort values and also strings alphabetically

#Sort an array
my_list.sort()    #Just this (no need for my_list= )
my_list.sort(reverse=True)    #Sort in reverse order

#Copy an array and then sort it
my_list_new = sorted(my_list)

Is value in list

if ('Hi' in my_list):
How many times does value occur in a list
num_of_times = my_list.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.

Comments

Your email address will not be published. Required fields are marked *