Perl & Python: Applying a Function to a List

Advertise Here

, 2005-01-17, 2011-07-25

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))

http://docs.python.org/lib/built-in-funcs.html

Perl

Removing Elements in a List

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

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

The $_ is a builtin variable that represent a argument given to a subroutine. $_[0] means the first argument. @_ is the entire arguments as array. The $_ is also the default input for regex to match, and in general represents a default argument.

The (0..10) generate a list from 0 to 10.

The % above is the operator for computing remainder of a division.

The Data::Dumper module is to import the “Dumper” function for printing list.

Applying a Function to a List

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

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

The ** is the exponential operator.

blog comments powered by Disqus