2.2 List Operations
.countreturns the frequency of an item.my_list.count('Monday').sortsorts the listmy_list.sortin assending order.reversereverses the ordermy_list.reversein decending orderminreturns the smallest itemmin(my_list)maxreturns the largest itemmax(my_list)sumreturns the sum of the itemssum(my_list)lenreturns the number of items on the list (size)len(my_list)
Example: what is the frequency count for the element "Monday" for the list x = ['Monday', 'Tuesday', 'Wednesday', 'Monday', 4, 5, 6, 4, 4, 7.0]?
x = ['Monday', 'Tuesday', 'Wednesday', 'Monday', 4, 5, 6, 4, 4, 7.0]
x.count('Monday')
Show expected output
2Example: Sort the list y = [10,14,20,15]. Print the sorted list.
y = [10,14,20,15]
y.sort()
y
Show expected output
[10, 14, 15, 20]Example: Use the sorted list y from above to reverse the order.
y = [10,14,20,15]
y.reverse() # revers order
y
Show expected output
[15, 20, 14, 10]Example: Use the list y = [10,14,20,15] above to find the minimum item of the list.
y = [10,14,20,15]
min(y)
Show expected output
10Example: Use the list y = [10,14,20,15] above to find the maximum item of the list.
y = [10,14,20,15]
max(y)
Show expected output
20Example: Use the list y = [10,14,20,15] above to find the sum of all items in the list.
y = [10,14,20,15]
sum(y)
Show expected output
59Example: Use the list y = [10,14,20,15] above to find the length of the list. That is, how many items are there in the list?
y = [10,14,20,15]
len(y)
Show expected output
4Example: Write a Python program that displays the sum, minimum, maximum and length of the values of the elements in a given list, x=[1,2,3,4,5,6,7,8,9]
x=[1,2,3,4,5,6,7,8,9]
print('the sum is:',sum(x))
print('the min is:',min(x))
print('the max is:',max(x))
print('the length is:',len(x))
Show expected output
the sum is: 45
the min is: 1
the max is: 9
the length is: 9Adapted from Python for Introductory Statistics, by Simon Aman (Truman College, City Colleges of Chicago), licensed under CC BY 4.0. Changes were made: reformatted as an accessible XYZ web edition with live in-browser code cells. License: CC-BY-4.0.