HomeMathComputingArtsWordsLiteratureMusictwitter facebook webfeed

Perl & Python: Applying a Function to a List

Advertise Here For Profit

Xah Lee, 2005-01-17

Python

Removing Elements in a List

To remove elements in a list that satisfies some criterion, use the function filter(testFunction,list). The “testFunction” will be applied to each element in the list. If testFunction(element) returns False, then that element will not be in the resulting list.

def even(n): return n % 2 == 0
print filter( even, range(11))

Applying a Function to a List

The “map” function applies a function to all elements of a list. Example:

def square(n): return n*n
print map(square, range(11))

Python Doc

Perl

Removing Elements in a List

Use “grep” to remove elements in a list. The form is grep {testFunction $_} myList. Example:

use Data::Dumper;
sub even {return $_[0]%2==0};
print Dumper[ grep {even $_} (0..10)];

In perl in general, $_ means the entire argument(s) given to a subroutine. $_[0] means the first argument. The (0..10) generate a list from 0 to 10.

Applying a Function to a List

Use “map” to apply a function to a list. The basic form is map {myFunction($_)} myList.

use Data::Dumper;
sub square {return ($_[0])**2;};
print Dumper [ map {square($_)} (0..10)];

The Data::Dumper module is to import the “Dumper” function for printing lists. The % is the operator for computing remainder. The ** is the exponential operator.

blog comments powered by Disqus