Index
Small or large amounts of data can be stored after each other in a list. In the same way, a string is called as such because it's a string of characters in a row after each other.
In this section, we will take lists and strings apart by using indexes and slices.
Because all data in a list is in a specified order, we can obtain the value at a specific location in a list - that location is called an index. The fact that all the values in a list are in a certain order means that we can see what is in a certain place by specifying an index.
Counting from zero
This is how we can print the first letter of a name:
name = input("What is your name?")
print(name[0])
In the world of the computer, we start counting from zero. So, the first letter is at index zero, the second letter is at index one, and so on.
To retreieve something from a specific location in a list or a string we use square brackets [ and ]. Between them, we write an index (location number), like above.
In the same way we can print the string "three" in the following way:
numbers = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"]
print(numbers[3])
If you specify a larger index than the size of the list you will get an error. For example, print(numbers[999]) would crash the program. The error message will mention an IndexError.
Slices
An index picks out a specific value from a list or a specific character from a string. But we can also pick out several values to a new list or string. We do this by specifiying two indexes, a start- and end-index.
s = "Yes, Python is a language."
language = s[5:11]
print(language) # prints "Python"
We call this this a slice of the string s, it's also called a "substring". The final value is not included (just as for range).
Kilometers
Linda has kept track of how many kilometers she has biked every day in February in a long list. Now, she's curious how much that is per week.
cycling_february = [3, 2, 7, 0, 2, 5, 12, 6, 2, 7, 0, 2, 5, 0, 0, 0, 4, 0, 2, 5, 25, 3, 2, 0, 0, 2, 10, 10]
From this list, she can create four new lists by slicing the original list. The first week consists of the first seven days, the first seven values of the list. We start counting at 0, so we want the values from index 0 to index 6. The week after starts at index 7 and contains 7 days more, and so on. This can be done as follow:
In this video, we make the turtle smarter by letting it understand that "F", "Forward" and "Move forward" are all the same instruction.
- Index: En specific place in a list or a string. The first place has index 0.
- Slice: A part of a list or a string, specified with a start and an end index.
- List: A list is a collection of data in order. Can also be known as "array" in other programming languages.
- String: Various pieces of text is called a string. Shortened to "str".