Skip to main content
Chemistry LibreTexts

2.12: List Functions

  • Page ID
    206279
  • Hypothes.is tag: s20iostpy12ualr
    Download Assignment: S20py12
    Movies File: movies.txt

    Learning Objectives

    Students will be able to:

    Content:

    • Explain how the following functions are used with lists: reverse(), sort(), max() & min()
    • explain how to use lists with files

    Process:

    • Write code that reverses and sorts lists
    • Write code that finds the largest or smallest element of a list
    • Write code that reads from a file into a list

    Prior Knowledge

    • Python concepts from previous activities

    Further Reading

     

    Model 1: List functions

    method is a function that “belongs to” an object. Some of the methods available with a list object are shown below. Some of the methods have already been used in the previous activity. To use the method, you access them with the name of the list followed by the method and arguments in parenthesis e.g. list.append(“new data").

    Some Python List Methods

    append() Add an element to the end of a list Index() Returns the index of the first matched item
    insert() Insert an item at the defined index Count() Returns the count of the number of items passes as an argument
    remove() removes an item from the list Sort() Sort items in a list in ascending order
    pop() removes and returns an element at the index Reverse() Reverse the order of items in the list
    clear() removes all items from the list    

     

     

    Python Program 1:
    letters = ['d', 'y', 'n', 'b', 'g', 'l', 'h', 'j', 'r', 'q', 't']
    print(letters)
    letters.reverse()
    print(letters)

     


     

    Critical Thinking Questions:

    1.  Enter and execute Python Program 1:
      1. What does the code print?
      2. What does the reverse() function do?
      3. Revise the Python Program 1 to use the sort() method on the letters list. Write the revised line of code here:
      4. Do the list methods make a permanent change to the list? (Hint: Use the variables window in Thonny and the Debug current script run option. Step through each line of code.)
      5. What happens if you add the following line of code to the program?
    print(letters.sort())
    1. The python predefined max() and min() functions can be used on multiple variables or with elements in a list. The ord() function will return the ASCII value for a character.
    Python Program 2:
    letters = ['d', 'y', 'n', 'b', 'g', 'l', 'h', 'j', 'r', 'q', 't']
    print(letters)
    print(max(letters))
    print(min(letters))
    a= max(letters)
    b = min(letters)
    print(ord(a))
    print(ord(b))

     

    1. Which values get returned for the max() and min() functions?
    2. How does the ASCII value relate to the values returned in these functions?
    3. How is the syntax of the max() and min() functions different from the list method? Which of these can be arguments in other functions? 

    Information: The member operation determines if a given item is an element of a list.  The operation returns True if the item is an element of the list and False otherwise. Syntax: <element> in <list name>.

    1. The following program demonstrates the member operation for a list. Enter and execute the program:  

     

    Python Program 3:
    numbers = [23,56,13,78,56,24,89,19,5]
    
    guess = int(input("Guess number between 1 and 100: "))
    
    print("Here is the list of numbers: ", end= " ")
    for x in numbers:
        print(x, end=" ")
    print()
    
    if guess in numbers:
        print("Good Job! ", guess," is in the list.")
    else:
        print("As you can see, ", guess, " is NOT in the list.")
    

    1.  Circle the line of code in Python Program 3 that uses the member operation.
    2. Edit the program so that if the number the user entered is not in the list, it is added to the list.  Print the list again to be sure the number is added to the list. Here is some sample output

    py2

     

    4. This exercise will guide you through writing a program that generates 100 numbers between 1 and 500 and puts them in a list. The program prints the numbers, sorts the numbers, reverses the order of the numbers, determines the number of times a given number is in the list and prints the largest and smallest number.

    list

    1. Create an empty list to store the number
    2. Create the code to generate 100 random numbers between 1 and 500 store then in the list
    3. Create the code to print the list without the brackets. Create a separate function for this since you will be printing the list several times.
    4. Write the code that sorts and then reverses the numbers.  (Does the order of these two lines of code matter?) Print the code after it is sorted and again after the numbers are reversed.
    5. Write the code that prompts the user for a number between 1 and 500 and prints how many times that number is in the list. If the number is not in the list print the message: “Sorry, your number is not here!”
    6. Print the largest and smallest number.
    7. Enter and execute the code from a-f. be sure that it executes properly. Examine the sample output to the right.
    8. To make the numbers appear in columns, replace the print statement in the print function with the following line of code: print("%3d" %x, end=" "). What causes the change in output format?

     

    5.  Enter and execute the following code.

     

    Python Program 4:
    import random
    outFile = open('numbers.txt','w')
    for x in range(100):
        outFile.write(str(random.randint(1,11)) + "\n")
    outFile.close()
    print("Done!")

     


    What does the program do?

     

    6.  Add the following code to the program above:

    myList = []
    inFile = open('numbers.txt','r')
    for y in range(100):
        myList.append(int(inFile.readline()))
    inFile.close()
    1. What does the program do once this code is added?
    2. Explain what the following line of code does:      
          inFile = open('numbers.txt','r')
    3. Explain what the following line of code does:                      
          myList.append(int(inFile.readline()))
    4. Add a final line of code to the program that prints the list.

     

     

     

     

    • Was this article helpful?