MODYFING LISTS

Now that we know how to create a list and access each of the items, it would be good to know how to modify the list. Specifically, we need to know how to change or add items to a list, as well as add and deleting or removing items. If only there were a lesson that would show us how to do that! Wait no longer and read below!

Before we begin, it’s important to know how to slice a list.

Slicing a List

Slicing allows us to access a range of items in a list using the slicing operator, which is a colon (:). Don’t confuse that with an emoticon. Let’s create a list and slice the items using both positive and negative indexing.

‘M’ ‘e’ ‘r’ ‘i’ ‘v’ ‘a’ ‘l’ ‘e’
0 1 2 3 4 5 6 7
-8 -7 -6 -5 -4 -3 -2 -1

Now that we have our list, use the sample code below to see how it works.

Sample Code

Let’s use the list above and slice it up. Copy the code below and paste it into the interpreter. Have a look at the results and see your teacher if you have any difficulties. Try changing some of the values to see what effect it will have on the output.

[python]
#Create the list (this will be easier when we learn about strings)
word = [‘M’, ‘e’, ‘r’, ‘i’, ‘v’, ‘a’, ‘l’, ‘e’]

#Print the list as a whole
print("The list elements are:", word)

#Print the 5th element in the list (remember that positive indexing starts at 0)
print ("The 5th element in the list is:", word[4])

#Print the 2nd to 6th elements
print ("The 2nd to 6th elements are:", word[1:6]) #Notice the use of the colon and numbers within the bracket
#Note that 6 in this case does not indicate index 6 but rather the 6th element in the list
print ("The 2nd to 6th elements are:", word[-7:-3]) #We can also use negative indexing

#Print from the 3rd element to the end of the list
print ("The 3rd element to the final one are:", word[2:]) #Notice that that it is blank after the colon? That represents the end of the list. In this case, there is no need to put an index value.

#Print from the 1st to 4th elements
print ("The 1st to 4th elements are:", word[:4]) #Notice that that it is blank before the colon? That represents the beginning of the list.
#In this case, there is no need to put an index value. Also, the 4 in this case represents the 4th element and NOT the index 4.

#Print all elements in the list
print ("The elements in the list are:", word[:]) #Both values are left blank as they represent the beginning and end of the list.

#Print the elements in decreasing order
#We can add a third value to the backet and that is the step value
#Our setup is then listName[start:stop:step], where step is 1 by default
#Let’s print every second letter in the list
print(word[::2])
#Leaving the first 2 values blank will allow you to print from the start to the end of the list

#Print the elements in reverse order
print(word[::-1])
#By using a negative value it will print from the end to the beginning

#Place the code below that will print every 2nd element between the first and sixth elements
#Your output should be [‘M’, ‘r’, ‘v’]
[/python]

Changing Items

A list in Python in mutable, which is just a fancy way of saying that the items withing the list can be changed. Just like when you assigned a variable, you can change the items in a list by using the assignment operator (=).

[python]
#Create a Grocery List
groceries = [‘loaf of bread’, ‘container of milk’, ‘stick of butter’, ‘granola bars’, ‘ice cream’]

#Print the List
print (groceries)
#output: [‘loaf of bread’, ‘container of milk’, ‘stick of butter’, ‘granola bars’, ‘ice cream’]

#Change ‘stick of butter’ to ‘margarine’
#Since ‘stick of butter’ has an index of 2, we will use that to assign it a value
groceries[2] = ‘margarine’
print (groceries)
#output: [‘loaf of bread’, ‘container of milk’, ‘margarine’, ‘granola bars’, ‘ice cream’]

#Change the 2nd to fourth items in the list
groceries[1:4] = [‘chocolate milk’, ‘yogurt’, ‘apples’]
print (groceries)
#output: [‘loaf of bread’, ‘chocolate milk’, ‘yogurt’, ‘apples’, ‘ice cream’]
[/python]

Sample Code

Copy the code above and execute it. Does it create the result you expected? Change the items in the list to see the different results. Try creating your own list and printing each of its items. As well, try different slicing options to see the outcome.

Adding Items

There are two ways that you can add elements to a list. You can add one item using the append method or add several items using the extend method. Note that you cannot simply add an item by using the assignment operator. Let’s look at this more closely.

[python]
#Create a Blank Grocery List
groceries = []
#Blank lists, by default, will come with one blank element.
#Bascially, once you created the groceries list it automatically will execute the code groceries[0]=""

#Set the value of the first item to ‘bread’
groceries[0] = ‘bread’
#Again, this is allowed since groceries[0] exists

#Let’s add an item by using the assignment operator
groceries[1] = ‘milk’
#THIS WON’T WORK SINCE groceries[1] DOES NOT EXIST. You will get an error.
[/python]

Since we can’t use the assignment operator, we will use append and extend.

Append and Extend

As stated before, append will add one element to the end of your list while extend will add multiple elements to the end of your list. Have a look below.

[python]
odd = [1, 3, 5]

odd.append(7)

print(odd)
# Output: [1, 3, 5, 7]

odd.extend([9, 11, 13])

print(odd)
# Output: [1, 3, 5, 7, 9, 11, 13]
[/python]

Notice how all elements were added to the END OF THE LIST. We will learn how to add elements to specific locations later.

Sample Code

Copy the code above and execute it. Does it create the result you expected? Change the items in the list to see the different results. Try creating your own list and altering it using append and extend.

Deleting and Removing

You can delete an element, a slice, or an entire list by using the keyword del. This will allow you to remove an element based on the index or delete the list entirely. See the sample code below.

[python]
school = [‘M’, ‘e’, ‘r’, ‘i’, ‘v’, ‘a’, ‘l’, ‘e’]

print(school)
#Output: [‘M’, ‘e’, ‘r’, ‘i’, ‘v’, ‘a’, ‘l’, ‘e’]

#Delete the element at index 3
del school[3]

print(school)
#Output: [‘M’, ‘e’, ‘r’, ‘v’, ‘a’, ‘l’, ‘e’]

#Delete from index 2 to the 4th element
del school[2:4]

print(school)
#Output: [‘M’, ‘e’, ‘a’, ‘l’, ‘e’]

#Delete the last element in the list
del school[-1]

print(school)
#Output: [‘M’, ‘e’, ‘a’, ‘l’]
#Great … now I’m hungry

#Delete the entire list
del school

print(school)
#Error: List not defined
[/python]

The remove will all you to delete elements as well but not you can refer to them by their value and not their index. Very handy if you are unsure where the value is stored. Will remove the first instance only.

The clear method will allow you to empty an entire list without deleting it.

[python][/python]

school = [‘M’, ‘e’, ‘r’, ‘i’, ‘v’, ‘a’, ‘l’, ‘e’]

#Delete all instances of the letter ‘e’
school.remove(‘e’) #Note how remove comes AFTER the name of the list and there is a dot in between.

print(school)
#Output: [‘M’, ‘r’, ‘i’, ‘v’, ‘a’, ‘l’, ‘e’]

#Clear the list
school.clear()

print(school)
#Output: []

Sample Code

Copy the code above and execute it. Does it create the result you expected? Change the items in the list to see the different results. Try creating your own list and altering it using append and extend.

Check Your Understanding

Before moving to the next section, let’s see how well you know the current material.

  1. Who are you? Write an application which asks for 5 first names, and stores them in a list entitled ‘names’. The user should be able to display all the names in the list from first to last as well as last to first, edit a specific name, display a specific name, and delete a specific name.

When you are done, be sure to view the sample solution.