20050111: list basics

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

# in Python, list can be done this way:
a = [0, 1, 2, 'more',4,5,6]
print a

# list can be joined with plus sign
b = a + [4,5,6]
print b

# list can be extracted by appending a square bracket with index
# negative index counts from right.
print b[2]
print b[-2]

# sublist extraction
print 'element from 2 to 4 is', a[2:4]

# replacing elements can be done like
print '2nd element now is:', a[2]

# sequence of elements can be changed by assiging to sublist directly
# the length of new list need not match the sublist
b[2:4]=['bi','tri','quad','quint', 'sex']
print 'new a is', b

# list can be nested
a = [3,4,[7,8]]
print 'nested list superb!', a

# append extra bracket to get element of nested list
print a[2][1]    # gives 8


# in perl, list is done with paren ().
# the at sign in front of variable is necessary.
# it tells perl that it is a list.
@a = (0,1,2,'three',4,5,6,7,8,9);

# perl can't print lists. To show a list content,
# load the package Data::Dumper, e.g.
use Data::Dumper;
print '@a is:', Dumper(\@a);

# the backslash in front of @a is to tell Perl
# that "get the "address" of the "array" @a".
# it is necessary in Dumper because Dumper is
# a function that takes a memory address.
# see perldoc -t Data::Dumper for the intricacies
# of the module.

# to join two lists, just enclose them with ()
@b = (3,4);
@c = (@a,@b);
print '\@c is', Dumper \@c;
# note: this does not create nested list.

# to extrat list element, append with [index]
# the index can be multiple for multiple elements
@b = @a[3,1,5];
print Dumper \@b;

# to replace parts, do
$a[3]= 333;
print ' is', Dumper \@a;
# note the dollar sign.
# this tells Perl that this data is a scalar
# as opposed to a multiple.
# in perl, variable of scalars such as numbers and strings
# starts with a dollar sign, while arrays (lists) starts with
# a at @ sign. (and harshes/dictionaries starts with %)
# all perl variables must start with one of $,@,%.

# one creates nested list  by
# embedding the memory address into the parent list
@b = (4,5, \@a, 7);
print 'nested list is', Dumper \@b;

# to extrat element from nested list,
$c = $b[2]->[1];
print '$b[2]=>[1] is', $c;

# the syntax of nested lists in perl is quite arty, see
# perldoc -t perldata

Site Timeline