Lists are the No1 python data structure you should know about and you will probably end up using them all the time throughout your coding endeavours.
This is the way you define an empty list and assign it to the variable my_list.
my_list = []
my_list = list()
You can put all kinds of other variables in a list, including numbers, strings, booleans, other lists, other data structures and so on.
my_list = [ 'a', 'b', 34.3456, 2, ['a', 1], True, False ]
A list is ordered and in python the count starts from 0. So you can select the 1st item, 2nd item in this manner.
my_list[0]
my_list[1]
There is also a negative indexing count from the end of the list. Careful, although previously we started counting from zero, in this case we start from -1. This is how you access the last element and then the one before it.
my_list[-1] # The last element
my_list[-2] # The second to last element
What if you want a subset of a list? In Python we can slices of a list using its indexing. Say we want to access the first 3 elements.
#We use the method list[start_index:end_index]
my_list[0:3]
#Keep in mind it works for the negative indexing too
my_list[-3:-1]
Sometimes you will want to reassign or update elements in a list. If you want to change an item in a specific index then you can do it like this. Let us change the 1st element of the list to ‘Hello World!’.
my_list[0] = 'Hello World!'
What will happen very often is you will want to add elements to an already existing list(usually with a for loop). One of the most useful python methods for lists is the .append() method. Let’s add the number 35 to the end of our list.
my_list.append(35)
Also if you want the same thing but in the start of the list you can use the .insert() method. Note here you need to specify an index, meaning the .insert() method takes 2 arguments in the manner .insert(your_index, your_element). Let us insert 1234 in the beginning of our list.
my_list.insert(0, 1234)
Now if you want to remove an element from you list you can do it by value or by index.
my_list.remove(34.3456) #Remove the element 34.3456
my_list.pop(2) #Remove the element 34.3456 by its index
Note that the .pop() method will also return the element you are removing. If you do not want that you can use the del function. The del function can also be used in a generalised manner to delete the entire list, or an element or a slice and more.
del my_list[2] #Deletes the element 34.3456
del my_list[0:3] #Deletes first 3 elements
del my_list #Deletes the entire list
One last thing that is quite handy. You can check if an element is in a list by evaluating this statement to true or false.
element in/not in list
'a' in my_list #will evaluate to True in our case
'a' not in my_list #will evaluate to False in our case