Slices in Python

Our first program will demonstrate the use of lists (similar to slices in some other languages) in Python. Here’s the full source code:

import copy

def main():
    # Unlike arrays, lists are typed only by the
    # elements they contain (not the number of elements).
    # An uninitialized list is empty and has length 0.
    s = []
    print("uninit:", s, s == None, len(s) == 0)

    # To create an empty list with non-zero length, use
    # list multiplication. Here we make a list of
    # strings of length 3 (initially None-valued).
    s = [None] * 3
    print("emp:", s, "len:", len(s), "cap:", len(s))

    # We can set and get just like with arrays.
    s[0] = "a"
    s[1] = "b"
    s[2] = "c"
    print("set:", s)
    print("get:", s[2])

    # len returns the length of the list as expected.
    print("len:", len(s))

    # In addition to these basic operations, lists
    # support several more that make them richer than
    # arrays. One is the append method, which
    # adds one or more new values to the end of the list.
    s.append("d")
    s.extend(["e", "f"])
    print("apd:", s)

    # Lists can also be copied. Here we create a
    # new list c with the same contents as s.
    c = s.copy()
    print("cpy:", c)

    # Lists support a "slice" operator with the syntax
    # list[low:high]. For example, this gets a slice
    # of the elements s[2], s[3], and s[4].
    l = s[2:5]
    print("sl1:", l)

    # This slices up to (but excluding) s[5].
    l = s[:5]
    print("sl2:", l)

    # And this slices up from (and including) s[2].
    l = s[2:]
    print("sl3:", l)

    # We can declare and initialize a variable for list
    # in a single line as well.
    t = ["g", "h", "i"]
    print("dcl:", t)

    # Lists can be compared for equality.
    t2 = ["g", "h", "i"]
    if t == t2:
        print("t == t2")

    # Lists can be composed into multi-dimensional data
    # structures. The length of the inner lists can
    # vary, unlike with multi-dimensional arrays.
    twoD = [[] for _ in range(3)]
    for i in range(3):
        inner_len = i + 1
        twoD[i] = [i + j for j in range(inner_len)]
    print("2d: ", twoD)

if __name__ == "__main__":
    main()

To run the program, save it as lists.py and use python:

$ python lists.py
uninit: [] False True
emp: [None, None, None] len: 3 cap: 3
set: ['a', 'b', 'c']
get: c
len: 3
apd: ['a', 'b', 'c', 'd', 'e', 'f']
cpy: ['a', 'b', 'c', 'd', 'e', 'f']
sl1: ['c', 'd', 'e']
sl2: ['a', 'b', 'c', 'd', 'e']
sl3: ['c', 'd', 'e', 'f']
dcl: ['g', 'h', 'i']
t == t2
2d:  [[0], [1, 2], [2, 3, 4]]

Note that while lists in Python are similar to arrays in some languages, they are more flexible and can be resized dynamically.

Check out the official Python documentation for more details on the design and implementation of lists in Python.

Now that we’ve seen lists, we’ll look at Python’s other key builtin data structure: dictionaries.