5 Built-in functions Let’s look in more detail at built-in functions often used with iterators. Two of Python’s built-in functions,$_{map()}$ and$_{filter()}$ duplicate the features of generator expressions: map(f, iterA, iterB, ...) returns an iterator over the sequence f(iterA[0], iterB[0]), f(iterA[1], iterB[1]), f(iterA[2], iterB[2]), ... . >>> def upper(s): ... return s.upper() >>> list(map(upper, [ 'sentence','fragment'])) ['SENTENCE', 'FRAGMENT'] >>> [upper(s) for s in ['sentence','fragment']] ['SENTENCE', 'FRAGMENT'] You can of course achieve the same effect with a list comprehension. filter(predicate, iter) returns an iterator over all the sequence elements that meet a certain condition, and is similarly duplicated by list comprehensions. A predicate is a function that returns the truth value of some condition; for use with$_{filter()}$ , the predicate must take a single value. >>> def is_even(x): ... return (x%2)==0 >>> list(filter(is_even, range(10 ))) [0, 2, 4, 6, 8] This can also be written as a list comprehension: >>> list(x for x in range(10 ) if is_even(x)) [0, 2, 4, 6, 8] enumerate(iter, start=0) counts off the elements in the iterable returning 2-tuples containing the count (from start ) and each element. >>> for item in enumerate(['subject','verb','object']): ... print(item) (0, 'subject') (1, 'verb') (2, 'object') f =open('data.txt ','r') for i, line in enumerate(f): if line.strip()=='': print('Blank line at line # %i '%i) >>> import random >>> # Generate 8 random numbers between [0, 10000) >>> rand_list=random.sample( range(10000 ),8) >>> rand_list [769, 7953, 9828, 6431, 8442, 9878, 6213, 2207] >>> sorted(rand_list) enumerate() is often used when looping through a list and recording the indexes at which certain conditions are met: sorted(iterable, key=None, reverse=False) collects all the elements of the iterable into a list, sorts the list, and returns the sorted result. The key and reverse arguments are passed through to the constructed list’s sort() method. (continues on next page) 10