Manipulating lists in python

From raju

subset a list based on another boolean array

    >>> a=['k', 'a', 'ma', 'raju']
    >>> b = [True, False, True, False]
    >>> a
    ['k', 'a', 'ma', 'raju']
    >>> b
    [True, False, True, False]
    >>> c = [i for (i,v) in zip(a, b) if v]
    >>> c
    ['k', 'ma']
    

Ref: http://stackoverflow.com/questions/18665873/filtering-a-list-based-on-a-list-of-booleans

list indices of all true values of an array

    >>> import numpy as np
    >>> a = np.zeros(shape=10, dtype=bool)
    >>> a = np.zeros(shape=10, dtype=bool); a[3:5] = True; a[7:9] = True; a
    array([False, False, False,  True,  True, False, False,  True,  True, False], dtype=bool)
    >>> from itertools import compress
    >>> b = list(compress(range(len(a)), a)); b
    [3, 4, 7, 8]
    

create a list of given length

    >>> a=[None]*10
    >>> a
    [None, None, None, None, None, None, None, None, None, None]
    >>> a[2] = 4
    >>> a
    [None, None, 4, None, None, None, None, None, None, None]
    >>> a[3] = [1,2,3]
    >>> a
    [None, None, 4, [1, 2, 3], None, None, None, None, None, None]
    

Ref:- http://stackoverflow.com/questions/983699/initialise-a-list-to-a-specific-length-in-python

string for SQL where clause

The idea here is to build a single string by enclosing each element of a list in quotes and then concatenating them.

    >>> days=['sun','mon','tue','wed','thu','fri','sat']
    >>> days
    ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat']
    >>> day_string = "'" + "', '".join(days) + "'"
    >>> day_string
    "'sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'"
    

useful links