1.3 Lists

A smart feature in Python is listing. You can create a list and then conduct a series of adjustments and operations on the list. In this chapter we will cover basic operations like indexing, slicing, adding, multiplying, and checking for membership. In addition, Python has some built-in functions for lists that we will cover.

Creating Lists

You create a list by inserting values in between brackets separated by commas.

shoppingList = ['milk', 'eggs', 'ham', 'toilet paper']
randomList = ['blue', 4, 87, 'rain', 'pikachu', 3, 'door']

Notice that both names and numbers can be included in the list, so the items in the list do not need to be of the same type. You can also add a number into the list, but classify it as a string type by inserting it in quotes '40'. So now Python won't recognize it as a number, but as a word.

Printing

We can print the contents of a list by simply using the print function.

print(shoppingList)

and this is how the output would look:

##########Output:########## 
['milk', 'eggs', 'ham', 'toilet paper']

Accessing Values in a List

We can access values in a list by printing the indexed spot of the value on the list. We use the square brackets to indicate which values we need printed.

Remember that indexing in Python starts from 0, so the indexing of items in a list starts from item 0, then item 1 and so on. You can see below how the shoppingList would be indexed in Python.

shoppingList = ['milk', 'eggs', 'ham', 'toilet paper']
 Index:         item 0  item 1  item 2    item 3

So if I wanted Python to get the value of the 2nd item in the shoppingList, I would actually ask it for the 1st item.

print(shoppingList[1])

##########Output:########## 
eggs

I can also ask python to print out more than one of the values on the list.
We use the colon to do this, as you can see in the example below.

print(randomList[0:3])

##########Output:########## 
['blue', 4, 87]

Here we have indexed from value 0 to value 3. Notice that it doesn't include value 3 in the output, because it only indexes TO it.

Updating a list

You can update a list by adding more values, replacing some of the values or deleting certain values.

To replace a value in a list, you simply index the spot on the list you wish to replace, and the give it the value you wish to replace it with. As you can see below it has replaced ham with butter.

shoppingList[2] = 'butter'
print(shoppingList)

##########Output:########## 
['milk', 'eggs', 'butter', 'toilet paper']

To add values to the list, we use the append expression. In the example below we add cheese to our shopping list, and it has added it to the end of the list.

shoppingList.append('cheese')
print(shoppingList)

##########Output:########## 
['milk', 'eggs', 'butter', 'toilet paper', 'cheese']

If we wanted to add an item to a certain position of the list without replacing any other values, we use the insert expression. In the following example I want to insert the item chicken in the 1st position of my shoppingList. The index for the 1st position is 0.

shoppingList.insert(0, 'chicken')
print(shoppingList)

##########Output:########## 
['chicken', 'milk', 'eggs', 'butter', 'toilet paper', 'cheese']

In order to delete items from a list, we use the remove expression as shown below.

shoppingList.remove('eggs')
print(shoppingList)

##########Output:########## 
['chicken', 'milk', 'butter', 'toilet paper', 'cheese']

We can also delete indexes from a list if we don't know the name of the item we want to remove. So for example if I wanted to remove the 3rd index of my list, I would use the del expression that is used below.

del shoppingList[3]
print(shoppingList)

##########Output:########## 
['chicken', 'milk', 'butter', 'cheese']

Basic List Operations

A number of basic operations can be conducted on lists, just like earlier with strings. We can use operations to acquire the length of a list, to add or multiply a list and to check for membership in a list.

To get the length of a list, we use the len() operation.

print(len(shoppingList))

##########Output:########## 
4

It is also possible to add lists together. So if we try to combine our shoppingList and randomList we simply create a new list that adds the them together.

combinedList = shoppingList + randomList
print(combinedList)

##########Output:########## 
['chicken', 'milk', 'butter', 'cheese', 'blue', 4, 87, 'rain', 'pikachu', 3, 'door']

We can multiply a list with a certain number, to repeat the list that amount of times. So if I wanted to have 4 of each of my grocery items in a list, I could times the list by 4 as done in the example below.

newShoppingList = shoppingList * 4
print(newShoppingList)

##########Output:########## 
['chicken', 'milk', 'butter', 'cheese', 'chicken', 'milk', 'butter', 'cheese', 'chicken', 'milk', 'butter', 'cheese', 'chicken', 'milk', 'butter', 'cheese']

The next operation shows us how to check whether a value is a member of the list or not. So if I wanted to check whether I have included pastry on my shopping list,
I would use the following operation:

print('pastry' in shoppingList)

##########Output:########## 
False

Python tells me that pastry is not on my shopping list.

If we wanted to check how many times an object appears in a list, we could use the count() function.
In the example below we check how many times the word butter appears in our newShoppingList (the one we multiplied by 4).

print(newShoppingList.count('butter'))

##########Output:########## 
4

Other smart functions for lists

If we want to sort our list in alphabetical order or by numerical value, we can use the sort() function.

shoppingList.sort()
print(shoppingList)

##########Output:########## 
['butter', 'cheese', 'chicken', 'milk']

Note: If we want to sort our list in reversed alphabetical order or from highest value to lowest value, we use the sort(reverse=True) command.

If we need to figure out what position a certain item of the list is in, we can use the index() function. In the example below, I will try to find out what position cheese has in my shoppingList.

print(shoppingList.index('cheese'))

##########Output:########## 
1

Python tells me that cheese is indexed as position 1 on my list.

We can use the max() function to get the max value of an item in a list. So if we try to print the max value of the shopping list what will we get?

print(max(shoppingList))

##########Output:########## 
milk

Notice that it prints out the word milk. This is because milk starts with the letter m, the is the furthest letter in the alphabet compared to the first letters of the other words. So the max value can be chosen by number or by alphabetical order all depending on the values in the list.

A similar operation can be done for getting the minimum value in a list.

print(min(shoppingList))

##########Output:########## 
butter

As you can see, the minimum value in a list containing string values is the word with the first letter that comes in alphabetical order. Here it was the letter b.

It is also possible to write a sentence, and then split up the letters in the sentence into a list. To do that we use the list() function. See the example below to understand how it works.

word = 'Hello there!'
letterList = list(word)
print(letterList)

##########Output:########## 
['H', 'e', 'l', 'l', 'o', ' ', 't', 'h', 'e', 'r', 'e', '!']

If we would like to add the letters of the word human to the above list, we could use the extend() function.

letterList.extend('human')
print(letterList)

##########Output:########## 
['H', 'e', 'l', 'l', 'o', ' ', 't', 'h', 'e', 'r', 'e', '!', 'h', 'u', 'm', 'a', 'n']

Exercises

Please complete one or both of these exercises.
Exercise 1:

  1. Make a list containing all your family's birth year.
  2. Add a friend's birthday to the list.
  3. Sort your list from lowest value to highest value.
  4. Print out the highest value in your list.
  5. Remove your dad's birth year from the list.
  6. Now times the list by 4.
  7. Add your birth year to the list again, however put it on the 5th position in the list.
  8. Use python to find out how many times your birth year is repeated in the list.
  9. How long is your list now?

Exercise 2:

  1. Create a list with 6 names of tv characters you know.
  2. Sort the list from a-z.
  3. Print out the max value of list, what name do you get and why?
  4. Split the 3rd word in the list up into letters.
  5. Add your own name to the new split-up list.
  6. Delete all the letters a,e,o from the list.
  7. How many letters are left in your list?

Summary of Code

#Here we create two lists, one with numeric values and one with string values:
myList = [1, 2, 3] 
myList2 = ['A', 'B', 'C', 'D']

#Here we print one of the lists:
print(myList)

#Here we get the value of the second item in our list:
print(myList[1])

#Here we get the value of the second to fourth item in our list:
print(myList2[1:3])

#Here we replace the second value in our list with a different value:
myList[1] = 4

#Here we add a new value to our list:
myList.append(5)

#Here we add a new value to our list, but also give it a specific position in the list:
myList2.insert(4, 'E')

#Here we delete a value from our list:
myList2.remove('A')

#Here I delete a value from my list, by only specifying its index (position in the list):
del myList[1]

#Here I get the length of my list:
print(len(myList))

#Here I add my two lists together:
newList = myList + myList2

#Here I multiply my list with itself a certain number of times:
multipliedList = myList*5

#Here I check whether the number 5 is part of my list or not:
print(5 in myList)

#Here I want to check how many times the number 3 appears in my list:
print(myList.count(3))

#Here I sort my list in alphabetical order from a-z or numerical order from 0 to infinity:
myList2.sort()

#Here I sort my list in reversed alphabetical order from z-a or reversed numerical order from infinity to 0:
myList2.sort(reversed=TRUE)

#Here I find out what position the letter B has in my list:
print(myList2.index('B'))

#Here I get the maximum value in my list:
print(max(myList))

#Here I get the minimum value in my list:
print(min(myList))

#Here I split up letters in a sentence to make a list out of those letters:
sentence = 'what a sunny day'
letterlist = list(sentence)

#Here I add the letters of another word to my list:
letterlist.extend('not')

results matching ""

    No results matching ""