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

Python, Ruby, Perl: List Basics

Xah Lee, , …,

Python

List Construction

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

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

Counting Elements

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

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

Getting a Element

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

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

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

Negative index counts from right.

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

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

# negative index counts from right

Getting Sublists

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

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

a = ["zero", "one", "two", "three", "four", "five"]
print a[1:4]                    # ⇒ ['one', 'two', 'three']

# if first index is ommited, default to 0
print a[:4]                     # ⇒ ['zero', 'one', 'two', 'three']

# if second index is ommited, default length of list. Effectively, up to last element
print a[0:]                     # ⇒ ['zero', 'one', 'two', 'three', 'four', 'five']

# get everything
print a[:]                     # ⇒ ['zero', 'one', 'two', 'three', 'four', 'five']

# negative counts from last. Not include last.
print a[0:-1]                   # ⇒ ['zero', 'one', 'two', 'three', 'four']

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›] = ‹new value›.

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

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

A slice (continuous sequence) of elements can be changed by assigning to a list directly. The length of the slice need not match the length of new list.

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

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

Nested Lists

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

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

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

Join 2 Lists

Lists can be joined with plus sign.

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

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

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

Ruby

List Construction

# -*- coding: utf-8 -*-
# ruby

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

Counting Elements

# -*- coding: utf-8 -*-
# ruby

a = ["more", 4, 6]
p a.length                      # ⇒ 3

Getting a Element

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

# -*- coding: utf-8 -*-
# ruby

a = ["more", 4, 6]
p a[1]                          # ⇒ 4

Negative index counts from right.

# -*- coding: utf-8 -*-
# ruby

a = ["more", 4, 6]
p a[-1]                         # ⇒ 6

Getting Sublists

Consecutive elements can be extracted using the form myList[‹startIndex›,‹count›].

# -*- coding: utf-8 -*-
# ruby

a = ["zero", "one", "two", "three", "four", "five"]
p a[0,2]                        # ⇒ ["zero", "one"]

# first is index, second is count.

Changing Elements

A element can be changed with the form mylist[‹index›] = ‹new value›.

# -*- coding: utf-8 -*-
# ruby

a = ["nilpotent", "unisex", "bisexual"]
a[2] = "two"
p a                            # ⇒ ["nilpotent", "unisex", "two"]

A slice (continuous sequence) of elements can be changed by assigning to a list directly. The length of the slice need not match the length of new list.

# -*- coding: utf-8 -*-
# ruby

a = ["nilpotent", "unisex", "bisexual", "tribadism", "quadriceps", "quintessence", "sex"]

# change 4 elements of list to a new list, starting at index 2
a[2,4] = ["x", "y"]
p a                             # ⇒ ["nilpotent", "unisex", "x", "y", "sex"]

Nested Lists

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

# -*- coding: utf-8 -*-
# ruby

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

Join 2 Lists

Lists can be joined with plus sign.

# -*- coding: utf-8 -*-
# ruby

b = ["a", "b"] + [7, 6]
p b                             # ⇒ ["a", "b", 7, 6]

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:

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

@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. For detail, see: Perl List vs Array — the Nether Mumble Jumble.

Counting Elements

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

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

@a = (4, 5, 6);                 # a list

print scalar(@a);               # prints 3. The length.

print @a + 0;               # prints 3. The 「+」 forces a scalar context.

Perl has a “list context” and “scalar context”. How things are evaluated depends on whether the thing is in list or scalar context. “Context” basically means what's adjacent.

When a list/array is in a scalar context, it returns its length. The function scalar forces things in a scalar context.

Adding Elements

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

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

use Data::Dumper;

# append to a list

@b = (1, 9);
push(@b, 3);                    # add a element to @b, at the end

print Dumper(\@b);              # [1, 9, 3]
# -*- coding: utf-8 -*-
# perl

use Data::Dumper;

# join lists

@a = (1, 9);
@b = (3, 4);
@c = ();

push(@c, @a, @b);               # @c is the joined list of @a and @b

print Dumper(\@c);              # [1, 9, 3, 4]

Perl automatically flatten array/lists, even if the new item added to list is a list. To force creating a nested list, you have to use square brackets, like this:

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

use Data::Dumper;

@a = (1, 9);
@b = (5, 6);

# create nested list
push(@a, \@b);

print Dumper(\@a);              # [1, 9, [5, 6]]

Technically, the backslash forces the list into a reference.

Getting Elements

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

# -*- coding: utf-8 -*-
# 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;               # ['three', 1, 5]

print $c, "\n";                 # 2

Changing Elements

To replace parts, just assign them. ⁖ $myarray[3] = 'rabbit';.

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

use Data::Dumper;

@a = (0, 1, 2, 'three', 4);
$a[3] = 'new';

print Dumper(\@a);              # [ 0, 1, 2, 'new', 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.

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

use Data::Dumper;

@b = (4, 5, [1, 2, [9, 8]], 7); # nested list

print Dumper \@b;               # [ 4, 5, [ 1, 2, [ 9, 8 ] ], 7 ]

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

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

use Data::Dumper;

@a=(1, 2, 3);
@b = (4, 5, \@a, 7);            # embed @a as sublist.

print '@b', Dumper \@b;     # [ 4, 5, [ 1, 2, 3 ], 7 ]

To extract element from nested list, use the form $myArray[‹index1›]->[‹index2›]->[‹index3›]….

# -*- coding: utf-8 -*-
# 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