List Operations

The three standard sequence operations (+, *, []) can be performed with lists, as well as tuples and strings.

The + operator creates a new list as the concatenation of the arguments. The

>>> 
["field"] + [2, 3, 4] + [9, 10, 11, 12]

['field', 2, 3, 4, 9, 10, 11, 12]


The * operator between lists and numbers (number * list or list * number) creates a new list that is a number of repetitions of the input list.

>>> 
2*["pass","don't","pass"]

['pass', "don't", 'pass', 'pass', "don't", 'pass']


The [] operator selects an character or a slice from the list. There are two forms. The first format is list [ index ] . Elements are numbered from 0 at beginning through the length. They are also number from -1 at the end backwards to -len( list ). The slice format is list [ start : end ] . Items from start to end -1 are chosen; there will be end start elements in the resulting list. If start is omitted it is the beginning of the list (position 0), if end is omitted it is the end of the list.

In the following example, we've constructed a list where each element is a tuple. Each tuple could be a pair of dice.

>>> 
l=[(6, 2), (5, 4), (2, 2), (1, 3), (6, 5), (1, 4)]

>>> 
l[2]

(2, 2)
>>> 
print l[:3], 'split', l[3:]

[(6, 2), (5, 4), (2, 2)] split [(1, 3), (6, 5), (1, 4)]
>>> 
l[-1]

(1, 4)
>>> 
l[-3:]

[(1, 3), (6, 5), (1, 4)]