Lists in Python List methods and functions List
- Slides: 5
Lists in Python List methods and functions
List methods Method Semantics list. append(x) Adds x to the right end of list, changes original list. sort() Sorts items of list, in place. Items must be comparable list. reverse() Reverses order of items in list in place list. index(x) Returns integer index of first (leftmost) occurrence of x Returns integer count of number of occurrences of x in list. count(x)
Notes about methods • These methods, append, sort, reverse, all change the original list. • If you need to retain the original list as well as keep the resulting list, use sorted(listname) and list(reversed(listname)) • Just as with strings, index will cause an exception and program crash if its search fails
List functions Function Semantics min (list) Returns the smallest element in the list, items must be comparable Returns the largest element in the list, items must be comparable max (list) sum (list) sorted (list) reversed (list) Returns the arithmetic total of all items in list, items must be numeric Returns a new copy of list in ascending order, items must be comparable Returns an iterator of the list in reverse order (use a list typecast to get the list)
Notes about functions and methods • When the previous two tables say “items must be comparable”, it means they must all be of numeric type, or they must all be strings. Mixing them will cause an exception and crash • When they say “in place” it means that it will change the original list. • For the sum function, items can be integer or float