Lists
We previously had a brief introduction to lists earlier in the course. Let's create a file list_practice.py and write the following:
# List of strings
face = ['eyes', 'nose', 'ears', 'mouth']
# List of numbers
favourite_numbers = [3, 42, 69, 7]
# Yes, any kind of number
more_numbers = [4.5, 2, 10.823]
# Empty list
nothing = []
# No limitation, mix and match
random_variable = 24 / 3
random_list = ['hill', 12, 'c', random_variable]
# Lists can be stored inside, you guessed it, lists!
listception = ['bob', ['damian', 'junior', 'stephen', 3], 9, 'rita', [67]]It's quite easy to make lists. It's also very easy to get an item from a list. Recall that lists are an ordered sequence of items. To get an item from a list, we can use the item's index - the position of a list item.
As you've noticed, the last item is one less than the length of the list. Let's say you didn't create the list, how would know it's length? Use the len function
Let's go back to more list indices
You can use negative numbers for list indices as well. Instead of going from left to right, you'll get the items from right to left.
You should also get accustomed to some common errors. Remember, errors are awesome because they tell us exactly what's wrong. Let's try the following:
If you try the above you should get:
So if ever you see that error you know that the list doesn't have an item for that index. Therefore your list could be missing items or the index is inappropriate for that list.
List Functions
Lists also come with useful functions that can changed the elements contained within. Let's look at how easy it is to add to a list:
append simply adds an item to the end of the list. You may be asking... why does that function come after the list and '.'? That's because, it's no ordinary function, it's a method. We'll learn more about them later when we discucss Classes and Objects. For now, think of lists as special variables that can store both data and functions, which we call methods.
Lists and If Statements
It's not hard to imagine that there'll be a time when you'd like to know if an item is inside a list. Luckily Python makes this dead simple:
Exercises
A list has a length of 4, what are its indices?
Consider the list
twelves = [12, 'twelve', [12.0]]. What are:twelves[1]twelves[2]twelves[-8]twelves[-1][0] / 3twelves[-3]
Consider
a = [12, 45, 88, 93, 232, 121]Add 33 to a
Add 90 to b
Sort b
Reverse a
Given list
l1 = ['morning', 'noon', 'evening']andl2 = [9.9, 3, 11.5], create a list l3 using list functions and operators so that it has [11.5, 9.9, 3, 'morning', 'noon', 'evening', 9.9, 3, 11.5].Write a function
is_waldo_herethat accepts a list of suspects. If 'waldo' is in the list then return "We can find Waldo, go search!". Otherwise return, "Maybe we'll find him... tomorrow!"
Last updated