Manipulating lists in python

From raju

print all items in a list that match a string

matches = [s for s in my_list if my_string in s]

Ref :- https://stackoverflow.com/questions/21151174/python-if-list-contains-string-print-all-the-indexes-elements-in-the-list-tha

Check if a variable is a list

 % python3
Python 3.5.3 (default, Jan 19 2017, 14:11:04) 
[GCC 6.3.0 20170118] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> isinstance(['foo'], list)
True
>>> isinstance('foo', list)
False

Convert string to a list of one element

 % python3
Python 3.5.3 (default, Jan 19 2017, 14:11:04) 
[GCC 6.3.0 20170118] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> a = 'foo'
>>> type(a)
<class 'str'>
>>> a
'foo'
>>> b = [a]
>>> type(b)
<class 'list'>
>>> b
['foo']

If you apply list() directly, each letter will be an element in the list.

>>> c = list(a)
>>> type(c)
<class 'list'>
>>> c
['f', 'o', 'o']

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'"

index of matching elements based on partial string

 % python
Python 2.7.13 (default, Nov 24 2017, 17:33:09) 
[GCC 6.3.0 20170516] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> mylist = ["aa123", "bb2322", "aa354", "cc332", "ab334", "333aa"]
>>> index = [i for i, s in enumerate(mylist) if 'aa' in s]
>>> index
[0, 2, 5]

>>> new_list = [mylist[i] for i in index]
>>> new_list
['aa123', 'aa354', '333aa']

tags | find the index of matching element in a list demonstrates | print list of lists

useful links