-
Integers, Floats and Strings 3
-
Lecture1.1
-
Lecture1.2
-
Lecture1.3
-
-
If Statements 3
-
Lecture2.1
-
Lecture2.2
-
Lecture2.3
-
-
Lists, Sets and Tuples 5
-
Lecture3.1
-
Lecture3.2
-
Lecture3.3
-
Lecture3.4
-
Lecture3.5
-
-
Loops 3
-
Lecture4.1
-
Lecture4.2
-
Lecture4.3
-
-
Functions 3
-
Lecture5.1
-
Lecture5.2
-
Lecture5.3
-
-
Dictionaries 3
-
Lecture6.1
-
Lecture6.2
-
Lecture6.3
-
-
Assertions 2
-
Lecture7.1
-
Lecture7.2
-
-
Classes 3
-
Lecture8.1
-
Lecture8.2
-
Lecture8.3
-
-
Matplotlib 2
-
Lecture9.1
-
Lecture9.2
-
Indexing
Pop¶
The function pop removes the last element and returns it to us. The following will remove 5 from the list since it is the last element, and return it to us.
#Pop removes the last variable from a list and returns it so that you can set a variable equal to it
#Here we take 5 from the list and assign its value to a
a = l.pop()
print(a)
print(l)
5
[1, 2, 4]
If given an index passed as an argument, pop will instead remove the element at that index and return it to us. Below we are going to grab the value of 2 because we passed in the index 1, and at that index is the number 2.
#If we say pop with a number then we pop but at that specific index
a = l.pop(1)
print(a)
print(l)
2
[1, 4]
Clear¶
Calling clear will get rid of all elements in a list.
#Clear gets rid of all elements in a list
l.clear()
print(l)
[]
More Indexing¶
We saw many of the basics for indexing when we did the lesson on strings, and these still apply, but let's see a few other methods.
Skipping Indices¶
When we want to find every second element, every third element, etc. we can use the following syntax l[i1:i2:i3] where i3 is the new index deciding if we get every second, third, etc element. In our first example, we will grab every second element. We will not include i1 or i2 meaning we are considering all elements!
l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
#Grab every second element
print(l[::2])
[1, 3, 5, 7, 9]
If we switch 2 to be 3, we get every third element.
#Get every third element
print(l[::3])
[1, 4, 7, 10]
We still can include i1, and this will change which of the elements we actually grab because it decides our starting point. Let's see the example with starting at 0 then starting at 1, and getting every second element.
#Grab every second element starting at index 0
print(l[0::2])
print()
#Grab every second element starting at index 1
print(l[1::2])
[1, 3, 5, 7, 9]
[2, 4, 6, 8, 10]
If we use a value for i2, it is in relation to the original list. What I mean by this is that if we do [0:4], we are first saying consider only the first 4 elements, then grab every second element. Below shows that we get only 2 elements back in both cases because we consider the numbers [1, 2, 3, 4] and [2, 3, 4] respectively.