Perl & Python: List Basics

Advertise Here

, 2005-01-11, 2011-07-23

Python

List Construction

a = [0, 1, 2, "more",4,5,6]
print a

Counting Elements

a = ["more",4,6]
print len(a) # prints 3

Getting a Element

List element can be extracted by appending a square bracket with index.

a = ["more",4,6]
print a[1] # prints 4

Negative index counts from right.

a = ["more",4,6]
print a[-1] # prints 6

Getting Sublists

Consecutive sequences can be extracted using the form myList[‹startIndex›:‹endIndex›].

a=["nil","uni","bi","tri","quad","quint","sex"]
print a[2:4]   # prints ["bi", "tri"]

WARNING: The extraction is not inclusive. For example, mylist[2:4] returns only 2 elements, not 3.

The easiest way to make sense of python's index is to think of it as between items. Like this:

list item  [ a , b , c , …]
            ↑  ↑   ↑   ↑
index       0  1   2   3

Changing Elements

A element can be changed with the form mylist[index]=val.

a=["nilpotent","unisex","bisexual"]
a[2]="two"
print a  # prints ['nilpotent', 'unisex', 'two']

A sequence of elements can be changed by assiging to sublist directly. The length of new list need not match the sublist.

a=["nilpotent","unisex","bisexual","tribadism","quadriceps","quintessence","sex"]
a[2:4]=["two","three"]
print a

Nested Lists

Lists can be nested arbitrarily. Append extra bracket to get element of nested list.

a = [3,4,[7,8]]
print a
print a[2][1]    # returns 8

Join 2 Lists

Lists can be joined with plus sign.

b = ["a","b"] + [7,6]
print b      # prints ['a', 'b', 7, 6]

http://docs.python.org/lib/typesseq-mutable.html

Perl

List Construction

In Perl, a list is created by enclosing elements in the parenthesis “()”. To assign a list to a variable, the variable must have a “@” sign in front. To print a list, use the “Dumper” function in the package “Data::Dumper”. Example:

@a = (0,1,2,'three',4,5,6,7); # assigns a list to @a.
use Data::Dumper; # loads the list-printing module
print '@a is:', Dumper(\@a);

The backslash in front of @a is necessary. It returns the “reference” of the array @a, and the argument to Dumper must be a reference. Once a list is assigned to a variable, it's called array. Don't worry about these details.

Counting Elements

To find the number of elements in a list, use “scalar”.

print scalar(@a);

Adding Elements

To add a element, or join two lists, use “push”.

# perl
use Data::Dumper;
@b = (1,9);
push(@b, 3);                    # add a element to b, at the end
print Dumper(\@b);             # [1, 9, 3]
# perl
use Data::Dumper;
@a = (1,9);
@b = (3,4);
@c = ();
push(@c, @a, @b); # @c is the joined list of @a and @b
print Dumper(\@c);

Getting Elements

To extract list element, append with [index]. The index can be several integers separated by comma, for getting multiple elements.

# perl
use Data::Dumper;
@a = (0,1,2,'three',4,5,6,7);
@b = @a[3,1,5];                 # ['three',1,5]
$c = @a[2];                     # gets 2

print Dumper \@b;
print $c, "\n";

Changing Elements

To replace parts, just assign them. e.g. $myarray[3] = 'hey';.

# perl

use Data::Dumper;

@a = (0,1,2,'three',4);
$a[3]= 'newValue';
print Dumper(\@a);               #  [ 0, 1, 2, 'newValue', 4 ]

Note the dollar sign $ above. This tells Perl that this data is a “scalar” as opposed to a “multiple”. In perl, a variable of “scalar” type (such as numbers and strings) starts with a $. A variable for array (aka list) starts with the sign @. A variable for harshes/dictionaries starts with %. All perl variables must start with one of {$ @ %}. (this is a simplified story)

Nested List

To create a nested list, use square brackets for the inner list. e.g. (1, 2, ['three','four'], 4).

# perl

use Data::Dumper;

@b = (4,5, [1, 2, [9,8]], 7);         # nested list
print '@b is:', Dumper \@b;           # [ 4, 5, [ 1, 2, [ 9, 8 ] ], 7 ]

You can embed a array as a nested list into another array. e.g. @b = (4,5, \@myarray, 7).

# perl

use Data::Dumper;

@a=(1,2,3);
@b = (4,5, \@a, 7);
print '@b is:', Dumper \@b;     # [ 4, 5, [ 1, 2, 3 ], 7 ]

To extract element from nested list, use the form $myArray[i1]->[i2]->[i3]….

# perl

use Data::Dumper;

@b = (1,2, ['x','y'], 3);
$c = $b[2]->[1];
print $c;                       # 'y'

@b = (1,2, ['x', [4,5], 7], 3);
$c = $b[2]->[1]->[1];
print $c;                       # 5

perldoc perldata

blog comments powered by Disqus