Learning objectives
By the end of this section you should be able to
- Use built-in functions
max()
,min()
, andsum()
. - Demonstrate how to copy a list.
Using built-in operations
The max()
function called on a list returns the largest element in the list. The min()
function called on a list returns the smallest element in the list. The max()
and min()
functions work for lists as long as elements within the list are comparable.
The sum()
function called on a list of numbers returns the sum of all elements in the list.
Example 9.3
Common list operations
"""Common list operations."""
# Set up a list of number
snum_list = [28, 92, 17, 3, -5, 999, 1]
# Set up a list of words
city_list = ["New York", "Missoula", "Chicago", "Bozeman",
"Birmingham", "Austin", "Sacramento"]
# Usage of the max() funtion
print(max(num_list))
# max() function works for strings as well
print(max(city_list))
# Usage of the min() funtion which also works for strings
print(min(num_list))
print(min(city_list))
# sum() only works for a list of numbers
print(sum(num_list))
The above code's output is:
999 Sacramento -5 Austin 1135
Concepts in Practice
List operations
Copying a list
The copy()
method is used to create a copy of a list.
Concepts in Practice
Copying a list
Try It
Copy
Make a copy of word_list
called wisdom. Sort the list called wisdom. Create a sentence using the words in each list and print those sentences (no need to add periods at the end of the sentences).