Python Tutorial (33) - Example: Common operations on lists

Time: Column:Python views:241

Python Lists: Definitions, Operations, and Examples

  1. Defining a List

    >>> li = ["a", "b", "mpilgrim", "z", "example"]
    >>> li
    ['a', 'b', 'mpilgrim', 'z', 'example']
    >>> li[1]
    'b'
  2. Negative Indexing in Lists

    >>> li
    ['a', 'b', 'mpilgrim', 'z', 'example']
    >>> li[-1]
    'example'
    >>> li[-3]
    'mpilgrim'
    >>> li[1:3]
    ['b', 'mpilgrim']
    >>> li[1:-1]
    ['b', 'mpilgrim', 'z']
    >>> li[0:3]
    ['a', 'b', 'mpilgrim']
  3. Adding Elements to a List

    >>> li
    ['a', 'b', 'mpilgrim', 'z', 'example']
    >>> li.append("new")
    >>> li
    ['a', 'b', 'mpilgrim', 'z', 'example', 'new']
    >>> li.insert(2, "new")
    >>> li
    ['a', 'b', 'new', 'mpilgrim', 'z', 'example', 'new']
    >>> li.extend(["two", "elements"])
    >>> li
    ['a', 'b', 'new', 'mpilgrim', 'z', 'example', 'new', 'two', 'elements']
  4. Searching in a List

    >>> li
    ['a', 'b', 'new', 'mpilgrim', 'z', 'example', 'new', 'two', 'elements']
    >>> li.index("example")
    5
    >>> li.index("new")
    2
    >>> li.index("c")
    Traceback (most recent call last):
      File "<interactive input>", line 1, in ?
    ValueError: list.index(x): x not in list
    >>> "c" in li
    False
  5. Removing Elements from a List

    >>> li
    ['a', 'b', 'new', 'mpilgrim', 'z', 'example', 'new', 'two', 'elements']
    >>> li.remove("z")
    >>> li
    ['a', 'b', 'new', 'mpilgrim', 'example', 'new', 'two', 'elements']
    >>> li.remove("new")    # Removes the first occurrence
    >>> li
    ['a', 'b', 'mpilgrim', 'example', 'new', 'two', 'elements']    # Second 'new' is not removed
    >>> li.remove("c")     # Raises an exception if the value is not found
    Traceback (most recent call last):
      File "<interactive input>", line 1, in ?
    ValueError: list.remove(x): x not in list
    >>> li.pop()      # Removes and returns the last element
    'elements'
    >>> li
    ['a', 'b', 'mpilgrim', 'example', 'new', 'two']
  6. List Operators

    >>> li = ['a', 'b', 'mpilgrim']
    >>> li = li + ['example', 'new']
    >>> li
    ['a', 'b', 'mpilgrim', 'example', 'new']
    >>> li += ['two']
    >>> li
    ['a', 'b', 'mpilgrim', 'example', 'new', 'two']
    >>> li = [1, 2] * 3
    >>> li
    [1, 2, 1, 2, 1, 2]
  7. Using join to Convert a List to a String

    >>> params = {"server":"mpilgrim", "database":"master", "uid":"sa", "pwd":"secret"}
    >>> ["%s=%s" % (k, v) for k, v in params.items()]
    ['server=mpilgrim', 'uid=sa', 'database=master', 'pwd=secret']
    >>> ";".join(["%s=%s" % (k, v) for k, v in params.items()])
    'server=mpilgrim;uid=sa;database=master;pwd=secret'

    Note: join can only be used with lists of strings; it does not perform any type conversion. Attempting to join a list with non-string elements will raise an exception.

  8. Splitting a String into a List

    >>> li = ['server=mpilgrim', 'uid=sa', 'database=master', 'pwd=secret']
    >>> s = ";".join(li)
    >>> s
    'server=mpilgrim;uid=sa;database=master;pwd=secret'
    >>> s.split(";")
    ['server=mpilgrim', 'uid=sa', 'database=master', 'pwd=secret']
    >>> s.split(";", 1)
    ['server=mpilgrim', 'uid=sa;database=master;pwd=secret']

    split is the opposite of join; it splits a string into a list of elements. Note that the delimiter (";") is completely removed and does not appear in the resulting list. The optional second parameter specifies the number of splits to make.

  9. List Comprehension

    >>> li = [1, 9, 8, 4]
    >>> [elem * 2 for elem in li]
    [2, 18, 16, 8]
    >>> li
    [1, 9, 8, 4]
    >>> li = [elem * 2 for elem in li]
    >>> li
    [2, 18, 16, 8]
  10. Dictionary Operations

    >>> params = {"server":"mpilgrim", "database":"master", "uid":"sa", "pwd":"secret"}
    >>> params.keys()
    dict_keys(['server', 'database', 'uid', 'pwd'])
    >>> params.values()
    dict_values(['mpilgrim', 'master', 'sa', 'secret'])
    >>> params.items()
    dict_items([('server', 'mpilgrim'), ('database', 'master'), ('uid', 'sa'), ('pwd', 'secret')])
    >>> [k for k, v in params.items()]
    ['server', 'database', 'uid', 'pwd']
    >>> [v for k, v in params.items()]
    ['mpilgrim', 'master', 'sa', 'secret']
    >>> ["%s=%s" % (k, v) for k, v in params.items()]
    ['server=mpilgrim', 'database=master', 'uid=sa', 'pwd=secret']
  11. Filtering Lists

    >>> li = ["a", "mpilgrim", "foo", "b", "c", "b", "d", "d"]
    >>> [elem for elem in li if len(elem) > 1]
    ['mpilgrim', 'foo']
    >>> [elem for elem in li if elem != "b"]
    ['a', 'mpilgrim', 'foo', 'c', 'd', 'd']
    >>> [elem for elem in li if li.count(elem) == 1]
    ['a', 'mpilgrim', 'foo', 'c']