MathCurvesSurfacesWallpaper GroupsGallerySoftwarePOV-Ray
ProgramingLinuxPerl PythonHTMLCSSJavaScriptPHPJavaEmacsUnicode ♥
Web Hosting by 1&1

List Comprehension in Python & Perl

Xah Lee, , …,

List Comprehension is a special syntax for building lists, or nested lists. You can use “for loops” to do exactly the same, but List Comprehension often makes the code shorter.

Python

Here's example of list comprehension, generating a list of i*2 with i from 1 to 3.

# -*- coding: utf-8 -*-
# python

myList = [ i*2 for i in [1,2,3] ]
print myList                    # prints [2, 4, 6]

Following example build a list of tuples of the form (i*2, i*3).

# -*- coding: utf-8 -*-
# python

myList = [ (i*2,i*3) for i in range(1,6)]
print myList      # prints [(2, 3), (4, 6), (6, 9), (8, 12), (10, 15)]

List comprehension syntax has the form [‹expression› for ‹var› in ‹list›] where ‹expression› is evaluated with ‹var› replaced by each element in ‹list›.

The iteration part can be nested. Example:

# -*- coding: utf-8 -*-
# python

myList = [ (i,j) for i in range(1,6)  for j in range(1,4) ]
print myList

# output
# [
#  (1, 1), (1, 2), (1, 3),
#  (2, 1), (2, 2), (2, 3),
#  (3, 1), (3, 2), (3, 3),
#  (4, 1), (4, 2), (4, 3),
#  (5, 1), (5, 2), (5, 3)
# ]

Perl

Perl does not have the “list comprehension” as it is. However, in general, functional programing's brevity is more easily achieved in Perl than Python.

Here's a example of generating a list of i*2 for i from 1 to 5:

# -*- coding: utf-8 -*-
# perl

@myList = map {$_ * 2} (1..5);

use Data::Dumper;
print Dumper(\@myList);

Here's a example of generating a list of pairs “[i*2,i*3]”.

# -*- coding: utf-8 -*-
# perl

@myList = map {[$_ * 2, $_ * 3]} (1..5);

use Data::Dumper;
print Dumper(\@myList);

Here's a example of generating a nested list involving 2 looping variables that's normally done with “list comprehension”. In Perl, it's just done with normal nested loops.

# -*- coding: utf-8 -*-
# perl

@myList=();
for ($i=1;$i<=5;$i++) {
  for ($j=1;$j<=3;$j++) {
    push (@myList, [$i,$j]);
  }
}

use Data::Dumper; $Data::Dumper::Indent=0;
print Dumper(\@myList);

# prints $VAR1 = [[1,1],[1,2],[1,3],[2,1],[2,2],[2,3],
# [3,1],[3,2],[3,3],[4,1],[4,2],[4,3],[5,1],[5,2],[5,3]];
blog comments powered by Disqus