Chapter 6, Lesson 2 Text

Chapter Six: Lists and Loops

Lesson Two: List Functions

 

The biggest advantage of using a Python list over a tuple is that lists can be changed after you initialize them. It is possible to add and remove items from the list or change items that are already in the list. In this lesson, we'll cover some common list and tuple management functions that you can use in your own code.

Functions That Work on Any List or Tuple

You are familiar with calling functions like print() and passing in parameters inside the parentheses. Many other built-in Python functions exist to do different jobs. There are three functions that will accept a list or tuple as an input parameter and tell you the number of items in the list or find the largest or smallest value in the list.

FunctionDescription>
len(<list or tuple>)Returns the integer number of items in the input list or tuple.
max(<list or tuple>)Returns the largest value found in the input list or tuple
min(<list or tuple>)Returns the smallest value found in the input list or tuple

 

Because these functions do not modify the contents, they will work on both lists and tuples. The example below declares a list of integers and a tuple of string values. Try running the code below to see sample output for each function!

Try It Now

The meaning of "max" and "min" is obvious when considering numeric input. But what does finding the "max" or "min" value means when looking at strings? By default, Python will use alphabetical ordering (like you would find in a dictionary) to find the minimum and maximum string values.

Functions That Work on a Specific List

Once you declare a specific list like myGrades or mySiblings, you can call several additional Python functions using that list variable name. In your code, you would write the variable name, then a dot (.), and then the function name. For example, "myGrades.append()" would be used to call the append() function on the list stored in the myGrades variable.

FunctionDescription>
append(<value to add>)Adds a new value to the end of the list.
insert(<index>,<value to add>)Adds a new value into the list before the specified index. Using 0 as the index will insert the value at the very beginning of the list.
remove(<value to remove>)Deletes the first value in the list that matches the input. If value is not found, a ValueError exception will be thrown at run-time!
pop(<index>)Deletes the value at the specified index, and returns that value so you can do something with it.
clear()Deletes all of the items in the list, leaving it empty.
index(<value to find>)Searches the list and returns the numeric index of the first element where the input value is found. A ValueError exception will be thrown at run-time if the value is not found!
count(<value to count>)Returns the number of times that the input value was found in the list.
sort()
sort(None,False)
Changes the order of items in the list so they are sorted from smallest to largest. If you add "None" and "False" parameters, the list will be sorted from largest to smallest instead.
reverse()Reverses the order of the values in the list.

 

Only two of these functions, index() and count(), will also work on tuples, because they do not change the contents of the tuple. All of the other functions result in some change to the list and will work only on lists.

The example below declares a list called fruityFlavors that holds several string values. We then practice calling each of the above functions on the list and print out the results. Study the code carefully and then run it. Do you get the expected output on each line?

Try It Now

Try changing the value to find for remove() or index() to something like "Blueberry" that is not in the list. You should get a ValueError exception when that function is run.

Traceback (most recent call last):
  File "code1.py", line 7, in <module>
    fruityFlavors.remove("Blueberry")
ValueError: list.remove(x): x not in list

Remember that exceptions will halt your program when it is running. So, you should carefully avoid making function calls that will cause exceptions at run-time.

Introducing the "in" Keyword

When working with lists, tuples or strings, you can use the "in" keyword to ask whether a particular value is present in that list, tuple or string. The logical expression "<value> in <list, tuple or string>" will return a Boolean True or False.

For example, the following code declares a list, and then asks if the value "Cherry" is in the list using "in". We store the result in a Boolean variable.

fruityFlavors = ["Cherry","Banana", "Grape", "Orange"]
isCherryPresent = "Cherry" in fruityFlavors              # should be True

Similarly, you could use "in" to ask if a letter or sub-string was present in a string. The two lines below checks the word "Cherry" to see if the letter "q" or the sub-string "rr" is present in the word.

result1 = "q" in "Cherry"    # should be False
result2 = "rr" in "Cherry"   # should be True

Of course, you can use the "in" keyword to form a logical expression in an "if" statement as well. You don't need to store the result in a variable.

if ("rr" in "Cherry"):    # should be True, so this "if" block will be run

Try running the sample code below and see the results for yourself! You can change the "in" expressions to produce True or False values based on the data in your target list or string.

Try It Now

 

The "in" keyword can also be used to form loops within your program, as you will see in the next lesson.

 

Work with Me: Collection Challenge

 

Are you ready to work with your new list management functions? Let's see if you can complete this challenge. You are going to start with the following list:

[3.14159, "Ahoy", True, 42, -1000, "Mmmmmm, ice cream"]

Your challenge is to use only the list-management functions described in this lesson to transform the list so it contains the following final values:

['Cookies', 'Second', 43, True, 'Ahoy', 3.14159]

Use the code window below to add your statements in the area shown by the comments. The program will start by printing the original list and end by printing the final list, which should match our target list.

Try It Now

  

There are many ways you could write code to turn the starting list into the final list. Our solution shows just one possible example.

End of Lesson


Last modified: Wednesday, 8 May 2019, 8:57 AM