OUTDATED, DO NOT USE: This tutorial was written in 1999 and was based on Python 1.5.2, which today is a really old version. I would not recommend using this tutorial to learn modern Python as the language has changed significantly. This page is left here in it's mostly-original form for historic reference only. Please consult the Python website for current documentation.

Indexing

  • Indexes start at 0, just like C
  • Negative indexes count backwards from the end:
    s = "ABCDEF"
    print s[0]   --> "A"
    print s[4]   --> "E"
    print s[-1]  --> "F"
    print s[-4]  --> "C"
    
  • Use the len() function to determine the size of the sequence.
    print len(s)  --> 6
    

Slicing

  • A slice is a contiguous portion of a sequence, uses syntax like s[ first:last ]. The last index is not included in the slice.
  • If the first index is ommitted, it will default to the first item (index 0).
  • If the last index is ommitted, it will default to the last item (index -1).
  • Both indexes can be ommitted (e.g., s[:]), which just means the entire sequence.
    s = "ABCDEF"
    s[2:5]  --> "CDE"
    s[4:]   --> "EF"
    s[:2]   --> "AB"
    s[:-1]  --> "ABCDE"
    s[-1:]  --> "F"
    s[:]    --> "ABCDEF"
    
  • A slice makes a new seqence, it does not modify the one you are slicing

Lists

  • Lists are sequences like strings, but can contain any type of element, not just characters. Lists are written like,
    [ 1, 5, "yellow" ]
    
  • Lists support all the same indexing and slicing operations as strings:
    L = [ "one", "two", "three" ]
    print L[0]   --> "one"
    print L[-1]  --> "three"
    print L[2:3] --> [ "two", "three" ]
    
  • Lists can even contain other lists
    L = [ "A", "B", [ "X", "Y" ], "C" ]
    print L[-1]     --> "C"
    print L[2]      --> ["X", "Y"]
    print L[2][-1]  --> "Y"
    print len(L)    --> 4
    
  • Empty lists are written []
  • Unlike strings, lists can be modified (you can only make new strings). The easiest way is to assign to indexes or slices.
    L = [ "red", "green", "blue" ]
    
    L[1] = "yellow"
    print L  --> ["red", "yellow", "blue"]
    
    L[1:2] = [ "purple", "orange", "white" ]
    print L  --> ["red", "purple", "orange", "white", "blue" ]
    
    L[:2] = ["pink"]
    print L  --> ["pink", "orange", "white", "blue"]
    
  • To add a new element to the end of the list use
    L.append( "cyan" )
    print L  --> ["pink", "orange", "white", "blue", "cyan"]
    
  • To delete an element, you could assign its slice to nothing,
    L[2:3] = []
    print L  --> ["pink", "orange", "blue", "cyan"]
    
    but python makes this easier with the del statment,
    S = [0,1,2,3,4]
    del S[2]
    print S  --> [0,1,3,4]
    del S[1:3]
    print S  --> [0,4]
    
  • There are other useful list methods too
    L.sort()
    print L   --> ["blue", "cyan", "orange", "pink"]
    
    L.reverse()
    print L   --> ["pink", "orange", "cyan", "blue"]
    
    L.insert(2, "brown")
    print L   --> ["pink", "orange", "brown", "cyan", "blue"]
    
    print L.index( "cyan" )  --> 3
    
    L.remove("orange")
    print L   --> ["pink", "brown", "cyan", "blue"]
    
    L.append("pink")
    print L.count( "pink" )  --> 2
    
  • If you want to make an independent copy of a list you can't just assign it to a different name. One popular method is by using the "everything" slice [:]. Look at the differences,
    A = [ 'trains', 'planes', 'cars' ]
    
    B = A
    C = A[:]
    
    A[3] = 'automobiles'  # now change one of the original items
    
    print B  --> ['trains', 'planes', 'automobiles']
    print C  --> ['trains', 'planes', 'cars']
    

Tuples

Besides strings and lists, there is one more sequence type built into Python: the tuple. Like a list, a tuple is an ordered sequence of arbitrary values. However, a tuple can not be modified.

  • Tuples are written like lists, only use () instead of []. Like lists they can contain anything, including other tuples or lists.
    t1 = ( 12, 700, 4 )
    t2 = ( "binary", [1,2,3], (3.14, "pi") )
    
  • Empty tuples are written as (). However to keep it from being confused with an expression, tuples with just one element need an extra comma
    t3 = ("a single valued tuple", )
    
  • Tuples can be indexed and sliced just like lists or strings. The result is a new tuple.
    T = ( "one", "two", "three", "four" )
    print T[1]   --> "two"
    print T[1:3] --> ("two","three")
    

Common sequence operations

All sequences (strings, lists, and tuples) support a common set of operations. They all support indexing and slicing. They also all support the following builtin functions

  • len() returns the number of elements in the sequence
    print len( "hotdog" )               --> 6
    print len( [9,2,5,3] )              --> 4
    print len( ('a','e','i','o','u') )  --> 5
    
  • min() and max() select the minimum and maximum values from the sequence using the natural ordering of the types it contains
    print min( [ 4, 8, 2 ] )  --> 2
    print max( [ 4, 8, 2 ] )  --> 8
    
    print min( [ 'lion', 'tiger', 'bear' ] )  --> "bear"
    print max( [ 'lion', 'tiger', 'bear' ] )  --> "tiger"
    
    print min( "cowboy" )  --> "b"
    print max( "cowboy" )  --> "y"
    
    print min( (4,8,2) )  --> "2"
    print max( (4,8,2) )  --> "8"
    
  • Lists of sequential numbers can be made using the range function
    print range(4)  --> [0,1,2,3]
    print range(7,9) --> [7,8,9]
    print range(-3,2) --> [-3,-2,-1,0,1]
    print range(200,100,-25)  --> [200,175,150,125]
    
  • It is common to use the range() function in a for-loop as an easy way to iterate a given number of times. If the number if really big though, it is more efficient to use the xrange() function, as in,
    # compute factorial of 1000
    product = 1L
    for i in xrange(1, 1000):
        product = product * i
    print 'The product of the first 1000 numbers is %d' % product
    
    (Technically, xrange produces a what is called a closure or a lazy-list. It only produces elements as they are used rather than creating the entire list all at once.)