get the list with the highest sum value in list `x`


get the value at index 1 for each tuple in the list of tuples `L`


create a set that is the exclusive or of [1, 2, 3] and [3, 4, 5]


if Selenium textarea element `foo` is not empty, clear the field


clear text from textarea 'foo' with selenium


make a function `f` that calculates the sum of two integer variables `x` and `y`

VAR_STR = lambda VAR_STR, VAR_STR: VAR_STR + VAR_STR


throw an error window in python in windows

ctypes.windll.user32.MessageBoxW(0, 'Error', 'Error', 0)


convert rows in pandas data frame `df` into list

VAR_STR.apply(lambda x: x.tolist(), axis=1)


split a unicode string `text` into a list of words and punctuation characters with a regex


sum all the values in a counter variable `my_counter`


convert 3652458 to string represent a 32bit hex number


print two numbers `10` and `20` using string formatting


replace placeholders in string '{1} {ham} {0} {foo} {1}' with arguments `(10, 20, foo='bar', ham='spam')`


insert string `string1` after each character of `string2`


check whether elements in list `a` appear only once


take screenshot 'screen.png' on mac os x


Reset the indexes of a pandas data frame


sort pandas data frame `df` using values from columns `c1` and `c2` in ascending order

df.sort(['c1', 'c2'], ascending=[True, True])

VAR_STR.sort(['VAR_STR', 'VAR_STR'], ascending=[True, True])


Get the zip output as list from the lists `[1, 2, 3]`, `[4, 5, 6]`, `[7, 8, 9]`

[list(a) for a in zip([VAR_STR], [VAR_STR], [VAR_STR])]


modify the width of a text control as `300` keeping default height in wxpython


How to erase the file contents of text file in Python?


Create sub matrix of a list of lists `[[2, 3, 4], [2, 3, 4], [2, 3, 4]]` (without numpy)


sort each row in a pandas dataframe `df` in descending order


Fastest way to sort each row in a pandas dataframe


delete all rows in a numpy array `a` where any value in a row is zero `0`


sort array `order_array` based on column 'year', 'month' and 'day'


Sort a structured numpy array 'df' on multiple columns 'year', 'month' and 'day'.


remove multiple values from a list `my_list` at the same time with index starting at `2` and ending just before `6`.


pandas read comma-separated CSV file `s` and skip commented lines starting with '#'


get a name of function `my_function` as a string


How to get a function name as a string in Python?


get a random record from model 'MyModel' using django's orm


in Django, select 100 random records from the database `Content.objects`


Merge all columns in dataframe `df` into one column


write a tuple of tuples `A` to a csv file using python


Write all tuple of tuples `A` at once into csv file


split string `s` to list conversion by ','

[x.strip() for x in VAR_STR.split('VAR_STR')]


delete all elements from a list `x` if a function `fn` taking value as parameter returns `0`

[VAR_STR for VAR_STR in lst if VAR_STR(VAR_STR) != 0]


execute command 'source .bashrc; shopt -s expand_aliases; nuke -x scriptPath' from python script

os.system('source .bashrc; shopt -s expand_aliases; nuke -x scriptPath')


Format all floating variables `var1`, `var2`, `var3`, `var1` to print to two decimal places.

print('%.2f kg = %.2f lb = %.2f gal = %.2f l' % (var1, var2, var3, var4))

print('%.2f kg = %.2f lb = %.2f gal = %.2f l' % (VAR_STR, VAR_STR, VAR_STR, var4))


Get the index value in list `p_list` using enumerate in list comprehension

{p.id: {'id': p.id, 'position': ind} for ind, p in enumerate(p_list)}

{p.id: {'id': p.id, 'position': ind} for ind, p in enumerate(VAR_STR)}


Python regular expression match whole word


Set the resolution of a monitor as `FULLSCREEN` in pygame


find button that is in li class `next` and assign it to variable `next`


match regex 'abc(de)fg(123)' on string 'abcdefg123 and again abcdefg123'

re.findall('abc(de)fg(123)', 'abcdefg123 and again abcdefg123')


Move the cursor of file pointer `fh1` at the end of the file.


Get the value of the minimum element in the second column of array `a`


create a list containing elements of list `a` if the sum of the element is greater than 10

[item for item in VAR_STR if sum(item) > 10]


to convert a list of tuples `list_of_tuples` into list of lists


group a list `list_of_tuples` of tuples by values


Add 1 to each integer value in list `my_list`


remove the last dot and all text beyond it in string `s`


merge lists `list_a` and `list_b` into a list of tuples


merge lists `a` and `a` into a list of tuples


How to select element with Selenium Python xpath


apply `numpy.linalg.norm` to each row of a matrix `a`


append dict `{'f': var6, 'g': var7, 'h': var8}` to value of key `e` in dict `jsobj['a']['b']`


read json `elevations` to pandas dataframe `df`


keep a list `dataList` of lists sorted as it is created by second element


sorting a list of tuples `list_of_tuples` where each tuple is reversed

sorted(list_of_tuples, key=lambda tup: tup[::-1])

sorted(VAR_STR, key=lambda tup: tup[::-1])


sorting a list of tuples `list_of_tuples` by second key

sorted(list_of_tuples, key=lambda tup: tup[1])


check if any values in a list `input_list` is a list

any(isinstance(el, list) for el in input_list)

any(isinstance(el, list) for el in VAR_STR)


check if string 'x' is  in list `['x', 'd', 'a', 's', 'd', 's']`


Get the first and last 3 elements of list `l`


remove a substring ".com" from the end of string `url`

if url.endswith('.com'):
    url = url[:(-4)]

if VAR_STR.endswith('VAR_STR'):
    VAR_STR = VAR_STR[:-4]


VAR_STR = re.sub('\\.com$', '', VAR_STR)


remove a substring `suffix` from the end of string `text`

if (not text.endswith(suffix)):
    return text
return text[:(len(text) - len(suffix))]

if not VAR_STR.endswith(VAR_STR):
    return VAR_STR
return VAR_STR[:len(VAR_STR) - len(VAR_STR)]


find the euclidean distance between two 3-d arrays `A` and `B`

np.sqrt(((VAR_STR - VAR_STR) ** 2).sum(-1))


split string `a` using new-line character '\n' as separator


split a string `a` with new line character


unpack the arguments out of list `params` to function `some_func`


python regex for hyphenated words in `text`


plot a bar graph from the column 'color' in the DataFrame 'df'


plot categorical data in series `df` with kind `bar` using pandas and matplotlib


generate random upper-case ascii string of 12 characters length

print(''.join(choice(ascii_uppercase) for i in range(12)))


python: dots in the name of variable in a format string


Replace each value in column 'prod_type' of dataframe `df` with string 'responsive'


python get time stamp on file `file` in '%m/%d/%Y' format


duplicate data in pandas dataframe `x` for 5 times

pd.concat([VAR_STR] * 5, ignore_index=True)


Get a repeated pandas data frame object `x` by `5` times


kill a process `make.exe` from python script on windows


check if all elements in list `mylist` are the same


draw a grid line on every tick of plot `plt`


find recurring patterns in a string '42344343434'


How to find all occurrences of an element in a list?

indices = [i for i, x in enumerate(my_list) if x == 'whatever']


create a dictionary using two lists`x` and `y`


generate a list from a pandas dataframe `df` with the column name and column values


check if all lists in list `L` have three elements of integer 1


Sort list `my_list` in alphabetical order based on the values associated with key 'name' of each dictionary in the list


display first 5 characters of string 'aaabbbccc'


Convert a list `['A:1', 'B:2', 'C:3', 'D:4']` to dictionary

dict(map(lambda s: s.split(':'), [VAR_STR]))


recursively go through all subdirectories and files in `rootdir`

for (root, subFolders, files) in os.walk(rootdir):
    pass

for root, subFolders, files in os.walk(VAR_STR):
    pass


sort list `X` based on values from another list `Y`

[x for y, x in sorted(zip(VAR_STR, VAR_STR))]


sorting list 'X' based on values from another list 'Y'


remove parentheses and text within it in string `filename`


find all `owl:Class` tags by parsing xml with namespace


Concatenate dataframe `df_1` to dataframe `df_2` sorted by values of the column 'y'


sum values greater than 0 in dictionary `d`

sum(v for v in list(d.values()) if v > 0)

sum(v for v in list(VAR_STR.values()) if v > 0)


Get all the items from a list of tuple 'l' where second item in tuple is '1'.


generate list of numbers in specific format using string formatting precision.


strip everything up to and including the character `&` from url `url`, strip the character `=` from the remaining string and concatenate `.html` to the end

VAR_STR.split('VAR_STR')[-1].replace('VAR_STR', '') + 'VAR_STR'


select a random element from array `[1, 2, 3]`


remove all non-alphabet chars from string `s`

"""""".join([i for i in s if i.isalpha()])

"""""".join([i for i in VAR_STR if i.isalpha()])


convert date strings in pandas dataframe column`df['date']` to pandas timestamps using the format '%d%b%Y'

df['date'] = pd.to_datetime(df['date'], format='%d%b%Y')

df['date'] = pd.to_datetime(df['date'], format='VAR_STR')


force bash interpreter '/bin/bash' to be used instead of shell

os.system('GREPDB="echo 123"; /bin/bash -c "$GREPDB"')


Run a command `echo hello world` in bash instead of shell

os.system('/bin/bash -c "echo hello world"')


get index values of pandas dataframe `df` as list


run app `app` on host '192.168.0.58' and port 9000 in Flask


print unicode string `ex\xe1mple` in uppercase


Get the sum of values to the power of their indices in a list `l`

sum(j ** i for i, j in enumerate(VAR_STR, 1))


get the first row, second column; second row, first column, and first row third column values of numpy array `arr`


Delete mulitple columns `columnheading1`, `columnheading2` in pandas data frame `yourdf`

yourdf.drop(['columnheading1', 'columnheading2'], axis=1, inplace=True)

VAR_STR.drop(['VAR_STR', 'VAR_STR'], axis=1, inplace=True)


Django get first 10 records of model `User` ordered by criteria 'age' of model 'pet'


run python script 'script2.py' from another python script, passing in 1 as an argument


create new column `A_perc` in dataframe `df` with row values equal to the value in column `A` divided by the value in column `sum`

VAR_STR['VAR_STR'] = VAR_STR['VAR_STR'] / VAR_STR['VAR_STR']


list duplicated elements in two lists `listA` and `listB`


extract digits in a simple way from a python string


find overlapping matches from a string `hello` using regex


Python / Remove special character from string


Sort list `keys` based on its elements' dot-seperated numbers

keys.sort(key=lambda x: map(int, x.split('.')))

VAR_STR.sort(key=lambda x: map(int, x.split('.')))


Sort a list of integers `keys` where each value is in string format

keys.sort(key=lambda x: [int(y) for y in x.split('.')])

VAR_STR.sort(key=lambda x: [int(y) for y in x.split('.')])


get the tuple in list `a_list` that has the largest item in the second index

max_item = max(a_list, key=operator.itemgetter(1))

max_item = max(VAR_STR, key=operator.itemgetter(1))


find tuple in list of tuples `a_list` with the largest second element


wait for shell command `p` evoked by  subprocess.Popen to complete


replace white spaces in dataframe `df` with '_'

VAR_STR.replace(' ', 'VAR_STR', regex=True)


switch positions of each two adjacent characters in string `a`

print(''.join(''.join(i) for i in zip(a2, a1)) + a[-1] if len(a) % 2 else '')

print(''.join(''.join(i) for i in zip(a2, a1)) + VAR_STR[-1] if len(VAR_STR) %
    2 else '')


[int(s) for s in re.findall('\\b\\d+\\b', "he33llo 42 I'm a 32 string 30")]


remove extra white spaces & tabs from a string `s`


get value of key `post code` associated with first index of key `places` of dictionary `data`


get a list of indices of non zero elements in a list `a`

[i for i, e in enumerate(VAR_STR) if e != 0]


Define a list with string values `['a', 'c', 'b', 'obj']`


repeat every character for 7 times in string 'map'

"""""".join(map(lambda x: x * 7, 'map'))

"""""".join(VAR_STR(lambda x: x * 7, 'VAR_STR'))


call a function with argument list `args`


restart a computer after `900` seconds using subprocess

subprocess.call(['shutdown', '/r', '/t', '900'])

subprocess.call(['shutdown', '/r', '/t', 'VAR_STR'])


abort a computer shutdown using subprocess


logoff computer having windows operating system using python


shutdown and restart a computer running windows from script


recursively delete all contents in directory `path`


convert pandas DataFrame `df` to a dictionary using `id` field as the key


convert pandas dataframe `df` with fields 'id', 'value' to dictionary


create list `new_list` containing the last 10 elements of list `my_list`


get the last 10 elements from a list `my_list`


Run 'test2.py' file with python location 'path/to/python' and arguments 'neededArgumetGoHere' as a subprocess


make new column 'C' in panda dataframe by adding values from other columns 'A' and 'B'

df['VAR_STR'] = df['VAR_STR'] + df['VAR_STR']


sum the length of lists in list `x` that are more than 1 item in length

sum(len(y) for y in VAR_STR if len(y) > 1)


replace each occurrence of the pattern '(http://\\S+|\\S*[^\\w\\s]\\S*)' within `a` with ''


check if dictionary `subset` is a subset of dictionary `superset`

all(item in list(superset.items()) for item in list(subset.items()))

all(item in list(VAR_STR.items()) for item in list(VAR_STR.items()))


check if elements in list `my_list` are coherent in order

return my_list == list(range(my_list[0], my_list[-1] + 1))

return VAR_STR == list(range(VAR_STR[0], VAR_STR[-1] + 1))


remove items from dictionary `myDict` if the item's value `val` is equal to 42

myDict = {key: val for key, val in list(myDict.items()) if val != 42}

VAR_STR = {key: VAR_STR for key, VAR_STR in list(VAR_STR.items()) if VAR_STR != 42}


Remove all items from a dictionary `myDict` whose values are `42`

{key: val for key, val in list(myDict.items()) if val != 42}

{key: val for key, val in list(VAR_STR.items()) if val != 42}


read the first line of a string `my_string`


How do I read the first line of a string?


extracting column `1` and `9` from array `data`


serve a static html page 'your_template.html' at the root of a django project


return the conversion of decimal `d` to hex without the '0x' prefix


Get multiple matched strings using regex pattern `(?:review: )?(http://url.com/(\\d+))\\s?`

pattern = re.compile('(?:review: )?(http://url.com/(\\d+))\\s?', re.IGNORECASE)

pattern = re.compile('VAR_STR', re.IGNORECASE)


get count of values in numpy array `a` that are between values `25` and `100`


replace only first occurence of string `TEST` from a string `longlongTESTstringTEST`


format current date to pattern '{%Y-%m-%d %H:%M:%S}'


count the number of pairs in dictionary `d` whose value equal to `chosen_value`

sum(x == chosen_value for x in list(d.values()))

sum(x == VAR_STR for x in list(VAR_STR.values()))


count the number of values in `d` dictionary that are predicate to function `some_condition`

sum(1 for x in list(d.values()) if some_condition(x))

sum(1 for x in list(VAR_STR.values()) if VAR_STR(x))


Get absolute folder path and filename for file `existGDBPath `


align values in array `b` to the order of corresponding values in array `a`


Join pandas data frame `frame_1` and `frame_2` with left join by `county_ID` and right join by `countyid`

pd.merge(frame_1, frame_2, left_on='county_ID', right_on='countyid')

pd.merge(VAR_STR, VAR_STR, left_on='VAR_STR', right_on='VAR_STR')


json.dumps({'apple': 'cat', 'banana': 'dog', 'pear': 'fish'})


get key-value pairs in dictionary `my_dictionary` for all keys in list `my_list` in the order they appear in `my_list`


sort json `ips_data` by a key 'data_two'

sorted_list_of_keyvalues = sorted(list(ips_data.items()), key=item[1]['data_two'])

sorted_list_of_keyvalues = sorted(list(VAR_STR.items()), key=item[1]['VAR_STR'])


remove empty strings from list `str_list`

str_list = list([_f for _f in str_list if _f])

VAR_STR = list([_f for _f in VAR_STR if _f])


do a `left` merge of dataframes `x` and `y` on the column `state` and sort by `index`

x.reset_index().merge(y, how='left', on='state', sort=False).sort('index')

VAR_STR.reset_index().merge(VAR_STR, how='VAR_STR', on='VAR_STR', sort=False).sort(
    'VAR_STR')


sort a list of dictionary `persons` according to the key `['passport']['birth_info']['date']`

sorted(persons, key=lambda x: x['passport']['birth_info']['date'])

sorted(VAR_STR, key=lambda x: x[VAR_STR])


change the background colour of the button `pushbutton` to red


Change log level dynamically to 'DEBUG' without restarting the application


resample series `s` into 3 months bins and sum each bin


Set colorbar range from `0` to `15` for pyplot object `quadmesh` in matplotlib


check if all boolean values in a python dictionary `dict` are true


return a random word from a word list 'words'


extract floating number from string 'Current Level: 13.4 db.'

re.findall('\\d+\\.\\d+', 'Current Level: 13.4 db.')


extract floating point numbers from a string 'Current Level: -13.2 db or 14.2 or 3'


split string `str` with delimiter '; ' or delimiter ', '


replace non-ascii chars from a unicode string u'm\xfasica'


convert a string `a` of letters embedded in squared brackets into embedded lists


Parse DateTime object `datetimevariable` using format '%Y-%m-%d'


get index of the first biggest element in list `a`


create dataframe `males` containing data of dataframe `df` where column `Gender` is equal to 'Male' and column `Year` is equal to 2014

males = df[(df[Gender] == 'Male') & (df[Year] == 2014)]

VAR_STR = VAR_STR[(VAR_STR[VAR_STR] == 'VAR_STR') & (VAR_STR[VAR_STR] == 2014)]


get a new string from the 3rd character to the end of the string `x`


get a new string including the first two characters of string `x`


get a new string including all but the last character of string `x`


get a new string including the last two characters of string `x`


get a new string with the 3rd to the second-to-last characters of string `x`


select alternate characters of "H-e-l-l-o- -W-o-r-l-d"


select a substring of `s` beginning at `beginning` of length `LENGTH`

VAR_STR = VAR_STR[VAR_STR:VAR_STR + VAR_STR]


Get a list of items in the list `container` with attribute equal to `value`

items = [item for item in container if item.attribute == value]

items = [item for item in VAR_STR if item.attribute == VAR_STR]


Get the indices in array `b` of each element appearing in array `a`


sort a list of lists `L` by index 2 of the inner list


sort a list of lists `l` by index 2 of the inner list


sort a list of lists `list_to_sort` by indices 2,0,1 of the inner list

sorted_list = sorted(list_to_sort, key=itemgetter(2, 0, 1))

sorted_list = sorted(VAR_STR, key=itemgetter(2, 0, 1))


Change data type of data in column 'grade' of dataframe `data_df` into float and then to int


get current url in selenium webdriver `browser`


Delete an item with key "key" from `mydict`


Delete an item with key `key` from `mydict`


try:
    del mydict[key]
except KeyError:
    pass
try:
    del mydict[key]
except KeyError:
    pass

try:
    del VAR_STR[VAR_STR]
except KeyError:
    pass
try:
    del VAR_STR[VAR_STR]
except KeyError:
    pass


run flask application `app` in debug mode.


Get total number of values in a nested dictionary `food_colors`

sum(len(x) for x in list(food_colors.values()))

sum(len(x) for x in list(VAR_STR.values()))


count all elements in a nested dictionary `food_colors`

sum(len(v) for v in food_colors.values())


concatenate sequence of numpy arrays  `LIST` into a one dimensional array along the first axis


read file 'myfile' using encoding 'iso-8859-1'


append `date` to list value of `key` in dictionary `dates_dict`, or create key `key` with value `date` in a list if it does not exist


build dictionary with keys of dictionary `_container` as keys and values of returned value of function `_value` with correlating key as parameter

{_key: _value(_key) for _key in _container}

{_key: VAR_STR(_key) for _key in VAR_STR}


load a tsv file `c:/~/trainSetRel3.txt` into a pandas data frame


regular expression matching all but 'aa' and 'bb' for string `string`


regular expression matching all but 'aa' and 'bb'


click on the text button 'section-select-all' using selenium python


regex for repeating words in a string `s`


get a dictionary with keys from one list `keys` and values from other list `data`


create a list containing the `n` next values of generator `it`


get list of n next values of a generator `it`

list(itertools.islice(VAR_STR, 0, n, 1))


convert csv file 'test.csv' into two-dimensional matrix

numpy.loadtxt(open('test.csv', 'rb'), delimiter=',', skiprows=1)

numpy.loadtxt(open('VAR_STR', 'rb'), delimiter=',', skiprows=1)


MySQL execute query 'SELECT * FROM foo WHERE bar = %s AND baz = %s' with parameters `param1` and `param2`

c.execute('SELECT * FROM foo WHERE bar = %s AND baz = %s', (param1, param2))


get data of columns with Null values in dataframe `df`


Collapse hierarchical column index to level 0 in dataframe `df`


get keys with same value in dictionary `d`

print([key for key in d if d[key] == 1])

print([key for key in VAR_STR if VAR_STR[key] == 1])


print([key for key, value in d.items() if value == 1])

print([key for key, value in VAR_STR.items() if value == 1])


Get keys from a dictionary 'd' where the value is '1'.

print([key for key, value in list(d.items()) if value == 1])

print([key for key, value in list(VAR_STR.items()) if value == 1])


coalesce non-word-characters in string `a`


variable number of digits `digits` in variable `value` in format string "{0:.{1}%}"


sort list `a` in ascending order based on the addition of the second and third elements of each tuple in it

sorted(a, key=lambda x: (sum(x[1:3]), x[0]))

sorted(VAR_STR, key=lambda x: (sum(x[1:3]), x[0]))


sort a list of tuples `a` by the sum of second and third element of each tuple

sorted(a, key=lambda x: (sum(x[1:3]), x[0]), reverse=True)

sorted(VAR_STR, key=lambda x: (sum(x[1:3]), x[0]), reverse=True)


sorting a list of tuples `lst` by the sum of the second elements onwards, and third element of the tuple

sorted(lst, key=lambda x: (sum(x[1:]), x[0]))

sorted(VAR_STR, key=lambda x: (sum(x[1:]), x[0]))


sort the list of tuples `lst` by the sum of every value except the first and by the first value in reverse order

sorted(lst, key=lambda x: (sum(x[1:]), x[0]), reverse=True)

sorted(VAR_STR, key=lambda x: (sum(x[1:]), x[0]), reverse=True)


multiply all items in a list `[1, 2, 3, 4, 5, 6]` together

from functools import reduce
reduce(lambda x, y: x * y, [1, 2, 3, 4, 5, 6])

from functools import reduce
reduce(lambda x, y: x * y, [VAR_STR])


create a list containing the subtraction of each item in list `L` from the item prior to it

[(y - x) for x, y in zip(VAR_STR, VAR_STR[1:])]


sympy solve matrix of linear equations `(([1, 1, 1, 1], [1, 1, 2, 3]))` with variables `(x, y, z)`


replacing 'ABC' and 'AB' values in column 'BrandName' of dataframe `df` with 'A'


replace values `['ABC', 'AB']` in a column 'BrandName' of  pandas dataframe `df` with another value 'A'

df['BrandName'] = df['BrandName'].replace(['ABC', 'AB'], 'A')

VAR_STR['VAR_STR'] = VAR_STR['VAR_STR'].replace([VAR_STR], 'VAR_STR')


Set time zone `Europe/Istanbul` in Django


match regex pattern 'TAA(?:[ATGC]{3})+?TAA' on string `seq`


remove the space between subplots in matplotlib.pyplot


convert js date object 'Tue, 22 Nov 2011 06:00:00 GMT' to python datetime

datetime.strptime('VAR_STR', '%a, %d %b %Y %H:%M:%S %Z')


order a list of lists `l1` by the first value


order a list of lists `[[1, 'mike'], [1, 'bob']]` by the first value of individual list


convert list of key-value tuples `[('A', 1), ('B', 2), ('C', 3)]` into dictionary


Check if tuple (2, 3) is not in a list [(2, 3), (5, 6), (9, 1)]


Check if tuple (2, 3) is not in a list [(2, 7), (7, 3), "hi"]


find consecutive consonants in a word `CONCENTRATION` using regex


add string `-` in `4th` position of a string `s`


check if character '-' exists in a dataframe `df` cell 'a'


Jinja2 formate date `item.date` accorto pattern 'Y M d'


Convert long int `myNumber` into date and time represented in the the string format '%Y-%m-%d %H:%M:%S'


remove leading and trailing zeros in the string 'your_Strip'


destruct elements of list `[1, 2, 3]` to variables `a`, `b` and `c`


get a list of characters in string `x` matching regex pattern `pattern`


get a list `slice` of array slices of the first two rows and columns from array `arr`

slice = [arr[i][0:2] for i in range(0, 2)]

VAR_STR = [VAR_STR[i][0:2] for i in range(0, 2)]


Create new list `result` by splitting each item in list `words`

result = [item for word in words for item in word.split(',')]

VAR_STR = [item for word in VAR_STR for item in word.split(',')]


sort list `lst` based on each element's number of occurrences

sorted(lst, key=lambda x: (-1 * c[x], lst.index(x)))

sorted(VAR_STR, key=lambda x: (-1 * c[x], VAR_STR.index(x)))


Insert a character `-` after every two elements in a string `s`

"""VAR_STR""".join(a + b for a, b in zip(VAR_STR[::2], VAR_STR[1::2]))


replace fields delimited by braces {} in string "Day old bread, 50% sale {0}" with string 'today'

"""Day old bread, 50% sale {0}""".format('today')


zip two lists `[1, 2]` and `[3, 4]` into a list of two tuples containing elements at the same index in each list


remove all instances of parenthesesis containing text beginning with `as ` from string `line`


decode a urllib escaped url string `url` with `utf8`


substitute multiple whitespace with single whitespace in string `mystring`


How can I split and parse a string in Python?


sort a list of tuples 'unsorted' based on two elements, second and third

sorted(unsorted, key=lambda element: (element[1], element[2]))

sorted(VAR_STR, key=lambda element: (element[1], element[2]))


converting byte string `c` in unicode string


sort list `files` based on variable `file_number`


parse a comma-separated string number '1,000,000' into int


multiply the columns of sparse matrix `m` by array `a` then multiply the rows of the resulting matrix by array `a`


print "Please enter something: " to console, and read user input to `var`

VAR_STR = input('Please enter something: ')


convert a set of tuples `queryresult` to a string `emaillist`

emaillist = '\n'.join(item[0] for item in queryresult)

VAR_STR = '\n'.join(item[0] for item in VAR_STR)


convert a set of tuples `queryresult` to a list of strings


convert a list of tuples `queryresult` to a string from the first indexes.

emaillist = '\n'.join([item[0] for item in queryresult])

emaillist = '\n'.join([item[0] for item in VAR_STR])


list the contents of a directory '/home/username/www/'


list all the contents of the directory 'path'.


Set multi index on columns 'Company' and 'date' of data frame `df` in pandas.


use upper case letters to print hex value `value`


Find all Chinese characters in string `ipath`


parse string "Jun 1 2005  1:33PM" into datetime by format "%b %d %Y %I:%M%p"

datetime.strptime('Jun 1 2005  1:33PM', '%b %d %Y %I:%M%p')


parse string "Aug 28 1999 12:00AM" into datetime


sort list `lst` with positives coming before negatives with values sorted respectively

sorted(VAR_STR, key=lambda x: (x < 0, x))


get tuples of the corresponding elements from lists `lst` and `lst2`

[(x, lst2[i]) for i, x in enumerate(lst)]

[(x, VAR_STR[i]) for i, x in enumerate(VAR_STR)]


create tuples containing elements that are at the same index of list `lst` and list `lst2`

[(i, j) for i, j in zip(VAR_STR, VAR_STR)]


get tuples from lists `lst` and `lst2` using list comprehension in python 2

[(lst[i], lst2[i]) for i in range(len(lst))]

[(VAR_STR[i], VAR_STR[i]) for i in range(len(VAR_STR))]


python, format string "{} %s {}" to have 'foo' and 'bar' in the first and second positions


replace string ' and ' in string `stuff` with character '/'


Execute SQL statement `sql` with values of dictionary `myDict` as parameters


set the size of figure `fig` in inches to width height of `w`, `h`


get value of first index of each element in list `a`


python how to get every first element in 2 dimensional list `a`


read file `fname` line by line into a list `content`

with open(fname) as f:
    content = f.readlines()

with open(VAR_STR) as f:
    VAR_STR = f.readlines()


read file 'filename' line by line into a list `lines`

with open('filename') as f:
    lines = f.readlines()

with open('VAR_STR') as f:
    VAR_STR = f.readlines()


lines = [line.rstrip('\n') for line in open('filename')]

VAR_STR = [line.rstrip('\n') for line in open('VAR_STR')]


read file "file.txt" line by line into a list `array`

with open('file.txt', 'r') as ins:
    array = []
    for line in ins:
        array.append(line)

with open('VAR_STR', 'r') as ins:
    VAR_STR = []
    for line in ins:
        VAR_STR.append(line)


Remove anything in parenthesis from string `item` with a regex


Remove word characters in parenthesis from string `item` with a regex


Remove all data inside parenthesis in string `item`


calculate ratio of sparsity in a numpy array `a`


"""""".join(c for c in my_string if c.isdigit())

"""""".join(c for c in VAR_STR if c.isdigit())


get all characters between two `$` characters in string `string`


getting the string between 2 '$' characters in '$sin (x)$ is an function of x'

re.findall('\\$(.*?)\\$', '$sin (x)$ is an function of x')


get list of string elements in string `data` delimited by commas, putting `0` in place of empty strings

[(int(x) if x else 0) for x in data.split(',')]

[(int(x) if x else 0) for x in VAR_STR.split(',')]


split string `s` into a list of strings based on ',' then replace empty strings with zero

""",""".join(x or '0' for x in s.split(','))

"""VAR_STR""".join(x or '0' for x in VAR_STR.split('VAR_STR'))


get a list of the keys in each dictionary in a dictionary of dictionaries `foo`

[k for d in list(foo.values()) for k in d]

[k for d in list(VAR_STR.values()) for k in d]


count `True` values associated with key 'one' in dictionary `tadas`

sum(item['one'] for item in list(tadas.values()))

sum(item['VAR_STR'] for item in list(VAR_STR.values()))


remove all duplicate items from a list `lseperatedOrblist`


prompt string 'Press Enter to continue...' to the console


customize the time format in python logging


reset index of dataframe `df`so that existing index values are transferred into `df`as columns


Get all the keys from dictionary `y` whose value is `1`


Sort list `li` in descending order based on the second element of each list inside list`li`


remove false entries from a dictionary `hand`

{k: v for k, v in list(hand.items()) if v}

{k: v for k, v in list(VAR_STR.items()) if v}


Get a dictionary from a dictionary `hand` where the values are present

dict((k, v) for k, v in hand.items() if v)

dict((k, v) for k, v in VAR_STR.items() if v)


sort a nested list by the inverse of element 2, then by element 1

sorted(l, key=lambda x: (-int(x[1]), x[0]))


count the number of words in a string `s`


get name of primary field `name` of django model `CustomPK`


sort a pandas data frame according to column `Peak` in ascending and `Weeks` in descending order

df.sort_values(['Peak', 'Weeks'], ascending=[True, False], inplace=True)

df.sort_values(['VAR_STR', 'VAR_STR'], ascending=[True, False], inplace=True)


sort a pandas data frame by column `Peak` in ascending and `Weeks` in descending order

df.sort(['Peak', 'Weeks'], ascending=[True, False], inplace=True)

df.sort(['VAR_STR', 'VAR_STR'], ascending=[True, False], inplace=True)


setup a smtp mail server to `smtp.gmail.com` with port `587`

server = smtplib.SMTP('smtp.gmail.com', 587)


execute external commands/script `your_own_script` with csh instead of bash


sum of product of combinations in a list `l`

sum([(i * j) for i, j in list(itertools.combinations(l, 2))])

sum([(i * j) for i, j in list(itertools.combinations(VAR_STR, 2))])


Truncate `\r\n` from each string in a list of string `example`

example = [x.replace('\r\n', '') for x in example]

VAR_STR = [x.replace('VAR_STR', '') for x in VAR_STR]


right align string `mystring` with a width of 7


creating a numpy array of 3d coordinates from three 1d arrays `x_p`, `y_p` and `z_p`

np.vstack(np.meshgrid(x_p, y_p, z_p)).reshape(3, -1).T

np.vstack(np.meshgrid(VAR_STR, VAR_STR, VAR_STR)).reshape(3, -1).T


move last item of array `a` to the first position


split string `Word to Split` into a list of characters


Sum of sums of each list, in a list of lists named 'lists'.


Set a window size to `1400, 1000` using selenium webdriver


change the case of the first letter in string `s`


get the sum of the products of each pair of corresponding elements in lists `a` and `b`

sum(x * y for x, y in zip(VAR_STR, VAR_STR))


sum the products of each two elements at the same index of list `a` and list `b`

list(x * y for x, y in list(zip(VAR_STR, VAR_STR)))


sum the product of each two items at the same index of list `a` and list `b`

sum(i * j for i, j in zip(VAR_STR, VAR_STR))


sum the product of elements of two lists named `a` and `b`

sum(x * y for x, y in list(zip(VAR_STR, VAR_STR)))


Split string `Hello` into a string of letters seperated by `,`


scatter(x, y, s=500, color='green', marker='h')


change the state of the Tkinter `Text` widget to read only i.e. `disabled`


display attribute `attr` for each object `obj` in list `my_list_of_objs`

print([obj.attr for obj in my_list_of_objs])

print([VAR_STR.VAR_STR for VAR_STR in VAR_STR])


lookup dictionary key `key1` in Django template `json`


Sum elements of tuple `b` to their respective elements of each tuple in list `a`

c = [[(i + j) for i, j in zip(e, b)] for e in a]

c = [[(i + j) for i, j in zip(e, VAR_STR)] for e in VAR_STR]


replace the last occurence of an expression '</div>' with '</bad>' in a string `s`


delete column 'column_name' from dataframe `df`


delete 1st, 2nd and 4th columns from dataframe `df`

VAR_STR.drop(VAR_STR.columns[[0, 1, 3]], axis=1)


delete a column `column_name` without having to reassign from pandas data frame `df`


Sort a data `a` in descending order based on the `modified` attribute of elements using lambda function

a = sorted(a, key=lambda x: x.modified, reverse=True)

VAR_STR = sorted(VAR_STR, key=lambda x: x.VAR_STR, reverse=True)


create a dictionary `list_dict` containing each tuple in list `tuple_list` as values and the tuple's first element as the corresponding key

list_dict = {t[0]: t for t in tuple_list}


print('\n'.join('  '.join(map(str, row)) for row in t))

print('\n'.join('  '.join(map(str, row)) for row in VAR_STR))


factorize all string values in dataframe `s` into floats


find out the number of non-matched elements at the same index of list `a` and list `b`

sum(1 for i, j in zip(VAR_STR, VAR_STR) if i != j)


Get all the second values from a list of lists `A`


extract first column from a multi-dimensional array `a`


print a celsius symbol on x axis of a plot `ax`


Convert list of dictionaries `L` into a flat dictionary

dict(pair for d in L for pair in list(d.items()))

dict(pair for d in VAR_STR for pair in list(d.items()))


merge a list of dictionaries in list `L` into a single dict

{k: v for d in L for k, v in list(d.items())}

{k: v for d in VAR_STR for k, v in list(d.items())}


compile Visual Studio project `project.sln` from the command line through python


read lines from a csv file `./urls-eu.csv` into a list of lists `arr`

arr = [line.split(',') for line in open('./urls-eu.csv')]

VAR_STR = [line.split(',') for line in open('VAR_STR')]


replace occurrences of two whitespaces or more with one whitespace ' ' in string `s`


count the number of rows with missing values in a pandas dataframe `df`

sum(df.apply(lambda x: sum(x.isnull().values), axis=1) > 0)

sum(VAR_STR.apply(lambda x: sum(x.isnull().values), axis=1) > 0)


Clicking a link using selenium using python


convert a string literal `s` with values `\\` to raw string literal

VAR_STR = VAR_STR.replace('VAR_STR', '\\\\')


get multiple integer values from a string 'string1'


sort list `l` based on its elements' digits

sorted(l, key=lambda x: int(re.search('\\d+', x).group(0)))

sorted(VAR_STR, key=lambda x: int(re.search('\\d+', x).group(0)))


get first element of each tuple in list `A`


Write a comment `# Data for Class A\n` to a file object `f`


Find the greatest number in set `(1, 2, 3)`


split string 'Words, words, words.' on punctuation

re.split('\\W+', 'Words, words, words.')


replace value '-' in any column of pandas dataframe to "NaN"


Generate a random integer between 0 and 9


Generate a random integer between `a` and `b`


Generate random integers between 0 and 9


get an element at index `[1,1]`in a numpy array `arr`


call `doSomething()` in a try-except without handling the exception


try:
    doSomething()
except Exception:
    pass


Create a list containing words that contain vowel letter followed by the same vowel in file 'file.text'

[w for w in open('file.txt') if not re.search('[aeiou]{2}', w)]


apply a list of functions named 'functions' over a list of values named 'values'

[x(y) for x, y in zip(functions, values)]

[x(y) for x, y in zip(VAR_STR, VAR_STR)]


Convert array `x` into a correlation matrix


reading tab-delimited csv file `filename` with pandas on mac


add multiple columns `hour`, `weekday`, `weeknum` to pandas data frame `df` from lambda function `lambdafunc`

df[['hour', 'weekday', 'weeknum']] = df.apply(lambdafunc, axis=1)

VAR_STR[['VAR_STR', 'VAR_STR', 'VAR_STR']] = VAR_STR.apply(VAR_STR, axis=1)


Check if a given key 'key1' exists in dictionary `dict`


Check if a given key `key` exists in dictionary `d`


remove multiple spaces in a string `foo`


Get the position of a regex match for word `is` in a string `String`


Get the position of a regex match `is` in a string `String`


get items from list `a` that don't appear in list `b`

[y for y in VAR_STR if y not in VAR_STR]


identify duplicated rows in columns 'PplNum' and 'RoomNum' with additional column in dataframe `df`

df.groupby(['PplNum', 'RoomNum']).cumcount() + 1

VAR_STR.groupby(['VAR_STR', 'VAR_STR']).cumcount() + 1


Jinja join elements of array `tags` with space string ' '


django urlsafe base64 decode string `uenc` with decryption


generate unique equal hash for equal dictionaries `a` and `b`


Get a list of strings `split_text` with fixed chunk size `n` from a string `the_list`

split_list = [the_list[i:i + n] for i in range(0, len(the_list), n)]

split_list = [VAR_STR[i:i + VAR_STR] for i in range(0, len(VAR_STR), VAR_STR)]


calculate the sum of the squares of each value in list `l`


get a list each value `i` in the implicit tuple `range(3)`


Filter Django objects by `author` with ids `1` and `2`


Write a regex statement to match 'lol' to 'lolllll'.


printing numbers rounding up to third decimal place


Plot using the color code `#112233` in matplotlib pyplot


remove 20 symbols in front of '.' in string 'unique12345678901234567890.mkv'


check if any element of list `substring_list` are in string `string`

any(substring in string for substring in substring_list)

any(substring in VAR_STR for substring in VAR_STR)


convert list `myintegers` into a unicode string


Make function `WRITEFUNCTION` output nothing in curl `p`

p.setopt(pycurl.WRITEFUNCTION, lambda x: None)

VAR_STR.setopt(pycurl.VAR_STR, lambda x: None)


split a string `s` at line breaks `\r\n`

[map(int, x.split('\t')) for x in s.rstrip().split('\r\n')]

[map(int, x.split('\t')) for x in VAR_STR.rstrip().split('VAR_STR')]


binarize the values in columns of list `order` in a pandas data frame

pd.concat([df, pd.get_dummies(df, '', '').astype(int)], axis=1)[order]

pd.concat([df, pd.get_dummies(df, '', '').astype(int)], axis=1)[VAR_STR]


Parse string '21/11/06 16:30' according to format '%d/%m/%y %H:%M'


Get the value with the maximum length in each column in array `foo`

[max(len(str(x)) for x in line) for line in zip(*foo)]

[max(len(str(x)) for x in line) for line in zip(*VAR_STR)]


finding words in string `s` after keyword 'name'


set data in column 'value' of dataframe `df` equal to first element of each list


get element at index 0 of each list in column 'value' of dataframe `df`


remove square bracket '[]' from pandas dataframe `df` column 'value'


Get a list from two strings `12345` and `ab` with values as each character concatenated

[(x + y) for x in '12345' for y in 'ab']

[(x + y) for x in 'VAR_STR' for y in 'VAR_STR']


sort keys of dictionary 'd' based on their values

sorted(VAR_STR, key=lambda k: VAR_STR[k][1])


sort list `student_tuples` by second element of each tuple in ascending and third element of each tuple in descending

print(sorted(student_tuples, key=lambda t: (-t[2], t[0])))

print(sorted(VAR_STR, key=lambda t: (-t[2], t[0])))


convert a list of lists `list_of_lists` into a list of strings keeping empty sub-lists as empty string ''


sort objects in `Articles` in descending order of counts of `likes`


divide each element in list `myList` by integer `myInt`

myList[:] = [(x / myInt) for x in myList]

VAR_STR[:] = [(x / VAR_STR) for x in VAR_STR]


format string with dict `{'5': 'you'}` with integer keys


Check if all elements in list `lst` are tupples of long and int

all(isinstance(x, int) for x in VAR_STR)


check if all elements in a list 'lst' are the same type 'int'

all(isinstance(x, VAR_STR) for x in VAR_STR)


sort a dictionary `y` by value then by key

sorted(list(y.items()), key=lambda x: (x[1], x[0]), reverse=True)

sorted(list(VAR_STR.items()), key=lambda x: (x[1], x[0]), reverse=True)


get mean of columns `2, 5, 6, 7, 8` for all rows in dataframe `df`


Create a key `key` if it does not exist in dict `dic` and append element `value` to value.


Convert each list in list `main_list` into a tuple


print('\n'.join(str(p) for p in myList))

print('\n'.join(str(p) for p in VAR_STR))


stack two dataframes next to each other in pandas

pd.concat([GOOG, AAPL], keys=['GOOG', 'AAPL'], axis=1)


add dictionary `{'class': {'section': 5}}` to key 'Test' of dictionary `dic`


replace everything that is not an alphabet or a digit with '' in 's'.


set size of `figure` to landscape A4 i.e. `11.69, 8.27` inches


django jinja slice list `mylist` by '3:8'


replace character 'a' with character 'e' and character 's' with character '3' in file `contents`

newcontents = contents.replace('a', 'e').replace('s', '3')

newcontents = VAR_STR.replace('VAR_STR', 'VAR_STR').replace('VAR_STR', 'VAR_STR')


unpack keys and values of a dictionary `d` into two lists

keys, values = zip(*list(VAR_STR.items()))


apply jinja2 filters `forceescape` and `linebreaks` on variable `my_variable`

{{my_variable | forceescape | linebreaks}}


parse string `s` to int when string contains a number

int(''.join(c for c in s if c.isdigit()))

int(''.join(c for c in VAR_STR if c.isdigit()))


check if any elements in one list `list1` are in another list `list2`


strip and split each line `line` on white spaces


Insert records in bulk from "table1" of "master" DB to "table1" of  sqlite3 `cursor` object

cursor.execute('INSERT OR REPLACE INTO master.table1 SELECT * FROM table1')

VAR_STR.execute('INSERT OR REPLACE INTO master.table1 SELECT * FROM table1')


Remove duplicates elements from list `sequences` and sort it in ascending order


decode utf-8 code `x` into a raw unicode literal


Compare if each value in list `a` is less than respective index value in list `b`

all(i < j for i, j in zip(VAR_STR, VAR_STR))


create a list containing keys of dictionary `d` and sort it alphabetically


extend dictionary `a` with key/value pairs of dictionary `b`


Delete character "M" from a string `s` using python

VAR_STR = VAR_STR.replace('VAR_STR', '')


How to delete a character from a string using python?


save xlsxwriter file in 'app/smth1/smth2/Expenses01.xlsx' path and assign to variable `workbook`


save xlsxwriter file to 'C:/Users/Steven/Documents/demo.xlsx' path


creating a 5x6 matrix filled with `None` and save it as `x`

x = [[None for _ in range(5)] for _ in range(6)]

VAR_STR = [[None for _ in range(5)] for _ in range(6)]


insert ' ' between every three digit before '.' and replace ',' with '.' in 12345678.46

format(12345678.46, 'VAR_STR').replace('VAR_STR', ' ').replace('VAR_STR', 'VAR_STR')


upload uploaded file from path '/upload' to Google cloud storage 'my_bucket' bucket

upload_url = blobstore.create_upload_url('/upload', gs_bucket_name='my_bucket')

upload_url = blobstore.create_upload_url('VAR_STR', gs_bucket_name='VAR_STR')


Group the values from django model `Article` with group by value `pub_date` and annotate by `title`


Retrieve list of values from dictionary 'd'


check if type of variable `s` is a string


check if type of a variable `s` is string


select all rows from pandas DataFrame 'df' where the value in column 'A' is greater than 1 or less than -1 in column 'B'.

VAR_STR[(VAR_STR['VAR_STR'] > 1) | (VAR_STR['VAR_STR'] < -1)]


check if all values in the columns of a numpy matrix `a` are same

np.all(VAR_STR == VAR_STR[(0), :], axis=0)


replace `0` with `2` in the list `[0, 1, 0, 3]`


Save array at index 0, index 1 and index 8 of array `np` to tmp file `tmp`

np.savez(tmp, *[getarray[0], getarray[1], getarray[8]])

VAR_STR.savez(VAR_STR, *[getarray[0], getarray[1], getarray[8]])


Getting the last element of list `some_list`


Getting the second to last element of list `some_list`


gets the `n` th-to-last element in list `some_list`


Produce a string that is suitable as Unicode literal from string 'M\\N{AMPERSAND}M\\N{APOSTROPHE}s'


Parse a unicode string `M\\N{AMPERSAND}M\\N{APOSTROPHE}s`


sum values in list of dictionaries `example_list` with key 'gold'

sum(item['gold'] for item in example_list)

sum(item['VAR_STR'] for item in VAR_STR)


get a sum of all values from key `gold` in a list of dictionary `example_list`

sum([item['gold'] for item in example_list])

sum([item['VAR_STR'] for item in VAR_STR])


Get all the values in key `gold` summed from a list of dictionary `myLIst`


replace '-' in pandas dataframe `df` with `np.nan`


disable logging while running unit tests in python django


normalize the dataframe `df` along the rows


Sort a string `s` in lexicographic order


get a sorted list of the characters of string `s` in lexicographic order, with lowercase letters first


insert a new field 'geolocCountry' on an existing document  'b' using pymongo

db.Doc.update({'_id': b['_id']}, {'$set': {'geolocCountry': myGeolocCountry}})

db.Doc.update({'_id': VAR_STR['_id']}, {'$set': {'VAR_STR': myGeolocCountry}})


pars a string 'http://example.org/#comments' to extract hashtags into an array


assign the index of the last occurence of `x` in list `s` to the variable `last`

VAR_STR = len(VAR_STR) - VAR_STR[::-1].index(VAR_STR) - 1


check if datafram `df` has any NaN vlaues


sum all elements of two-dimensions list `[[1, 2, 3, 4], [2, 4, 5, 6]]]`


Print a dictionary `{'user': {'name': 'Markus'}}` with string formatting

"""Hello {user[name]}""".format(**{'user': {'name': 'Markus'}})


Add 100 to each element of column "x" in dataframe `a`

a['x'].apply(lambda x, y: x + y, args=(100,))

VAR_STR['VAR_STR'].apply(lambda VAR_STR, y: VAR_STR + y, args=(100,))


get a list of of elements resulting from splitting user input by commas and stripping white space from each resulting string `s`

[VAR_STR.strip() for VAR_STR in input().split(',')]


encode `u'X\xc3\xbcY\xc3\x9f'` as unicode and decode with utf-8


Jinja parse datetime object `car.date_of_manufacture` to use format pattern `datetime`


Get the date object `date_of_manufacture` of object `car` in string  format '%Y-%m-%d'


convert a DateTime string back to a DateTime object of format '%Y-%m-%d %H:%M:%S.%f'


Pandas: How can I use the apply() function for a single column?

df['a'] = df['a'].apply(lambda x: x + 1)


split string 'happy_hats_for_cats' using string '_for_'


Split string 'sad_pandas_and_happy_cats_for_people' based on string 'and', 'or' or 'for'


Split a string `l` by multiple words `for` or `or` or `and`

[re.split('_(?:f?or|and)_', s) for s in l]

[re.split('_(?:f?or|and)_', s) for s in VAR_STR]


get the path of Python executable under windows


how to format a list of arguments `my_args` into a string


search and split string 'aaa bbb ccc ddd eee fff' by delimiter '(ddd)'

re.split('(ddd)', 'aaa bbb ccc ddd eee fff', 1)


regex search and split string 'aaa bbb ccc ddd eee fff' by delimiter '(d(d)d)'

re.split('(d(d)d)', 'aaa bbb ccc ddd eee fff', 1)


unescape special characters without splitting data in array of strings `['I ', u'<', '3s U ', u'&', ' you luvz me']`


output first 100 characters in a string `my_string`


convert a dataframe `df`'s column `ID` into datetime, after removing the first and last 3 letters


create a list with permutations of string 'abcd'


prepend string 'hello' to all items in list 'a'


get the opposite diagonal of a numpy array `array`


get the average of a list values for each key in dictionary `d`)

[(i, sum(j) / len(j)) for i, j in list(d.items())]

[(i, sum(j) / len(j)) for i, j in list(VAR_STR.items())]


get domain/host name from request object in Django


sort list `bar` by each element's attribute `attrb1` and attribute `attrb2` in reverse order

bar.sort(key=lambda x: (x.attrb1, x.attrb2), reverse=True)

VAR_STR.sort(key=lambda x: (x.VAR_STR, x.VAR_STR), reverse=True)


Represent DateTime object '10/05/2012' with format '%d/%m/%Y' into format '%Y-%m-%d'


find a tag `option` whose `value` attribute is `state` in selenium

driver.find_element_by_xpath("//option[@value='" + state + "']").click()

driver.find_element_by_xpath("//option[@value='" + VAR_STR + "']").click()


write a regex pattern to match even number of letter `A`


group rows of pandas dataframe `df` with same 'id'


onlyfiles = [f for f in listdir(mypath) if isfile(join(mypath, f))]

onlyfiles = [f for f in listdir(VAR_STR) if isfile(join(VAR_STR, f))]


f = []
for (dirpath, dirnames, filenames) in walk(mypath):
    f.extend(filenames)
    break

f = []
for dirpath, dirnames, filenames in walk(VAR_STR):
    f.extend(filenames)
    break


list all ".txt" files of a directory "/home/adam/"


list all files of a directory "somedirectory"


call parent class `Instructor` of child class constructor


Get all the texts without tags from beautiful soup object `soup`


format a string `num` using string formatting


extract the first four rows of the column `ID` from a pandas dataframe `df`


Convert escaped utf string to utf string in `your string`


count the number of True values associated with key 'success' in dictionary `d`

sum(1 if d['success'] else 0 for d in s)

sum(1 if VAR_STR['VAR_STR'] else 0 for VAR_STR in s)


get the sum of values associated with the key ‘success’ for a list of dictionaries `s`


replace unicode character '\u2022' in string 'str' with '*'


replace unicode characters ''\u2022' in string 'str' with '*'


Spawn a process to run python script `myscript.py` in C++


create file 'x' if file 'x' does not exist

fd = os.open('x', os.O_WRONLY | os.O_CREAT | os.O_EXCL)

fd = os.open('VAR_STR', os.O_WRONLY | os.O_CREAT | os.O_EXCL)


How to split a string into integers in Python?


getting a list of all subdirectories in the directory `directory`


get a list of all subdirectories in the directory `directory`


update the dictionary `mydic` with dynamic keys `i` and values with key 'name' from dictionary `o`


get a list of variables from module 'adfix.py' in current module.

print([item for item in dir(adfix) if not item.startswith('__')])


update dictionary `b`, overwriting values where keys are identical, with contents of dictionary `d`


read excel file `file_name` using pandas

dfs = pd.read_excel(file_name, sheetname=None)

dfs = pd.read_excel(VAR_STR, sheetname=None)


Find all words containing letters between A and Z in string `formula`


How can I launch an instance of an application using Python?


create a flat dictionary by summing values associated with similar keys in each dictionary of list `dictlist`

dict((key, sum(d[key] for d in dictList)) for key in dictList[0])


Remove all items from a dictionary `d` where the values are less than `1`

d = dict((k, v) for k, v in d.items() if v > 0)

VAR_STR = dict((k, v) for k, v in VAR_STR.items() if v > 0)


Filter dictionary `d` to have items with value greater than 0

d = {k: v for k, v in list(d.items()) if v > 0}

VAR_STR = {k: v for k, v in list(VAR_STR.items()) if v > 0}


split string 'fooxyzbar' based on case-insensitive matching using string 'XYZ'


BeautifulSoup find tag 'div' with styling 'width=300px;' in HTML string `soup`


send a signal `signal.SIGUSR1` to the current process


check if all elements in list `myList` are identical


format number of spaces between strings `Python`, `:` and `Very Good` to be `20`


How to convert a string from CP-1251 to UTF-8?


get rid of None values in dictionary `kwargs`

res = {k: v for k, v in list(kwargs.items()) if v is not None}

res = {k: v for k, v in list(VAR_STR.items()) if v is not None}


res = dict((k, v) for k, v in kwargs.items() if v is not None)

res = dict((k, v) for k, v in VAR_STR.items() if v is not None)


concatenate a list of strings `['a', 'b', 'c']`


split a multi-line string `inputString` into separate strings


Split a multi-line string ` a \n b \r\n c ` by new line character `\n`


concatenate elements of list `b` by a colon ":"

"""VAR_STR""".join(str(x) for x in VAR_STR)


Calculate sum over all rows of 2D numpy array


concatenate items of list `l` with a space ' '


run script 'hello.py' with argument 'htmlfilename.htm' on terminal using python executable


How can I parse a time string containing milliseconds in it with python?


convert a string `my_string` with dot and comma into a float number `my_float`

my_float = float(my_string.replace(',', ''))

VAR_STR = float(VAR_STR.replace(',', ''))


convert a string `123,456.908` with dot and comma into a floating number


split string 'Words, words, words.' using a regex '(\\W+)'

re.split('(\\W+)', 'Words, words, words.')


argparse add argument with flag '--version' and version action of '%(prog)s 2.0' to parser `parser`

parser.add_argument('--version', action='version', version='%(prog)s 2.0')


{i: VAR_STR[i] for i in VAR_STR if i != 'VAR_STR'}


Create new DataFrame object by merging columns "key" of  dataframes `split_df` and `csv_df` and rename the columns from dataframes `split_df` and `csv_df` with suffix `_left` and `_right` respectively

pd.merge(split_df, csv_df, on=['key'], suffixes=('_left', '_right'))

pd.merge(VAR_STR, VAR_STR, on=['VAR_STR'], suffixes=('VAR_STR', 'VAR_STR'))


Split a string `s` by space with `4` splits


enable debug mode on Flask application `app`


python save list `mylist` to file object 'save.txt'


Create 3d array of zeroes of size `(3,3,3)`


cut off the last word of a sentence `content`


x = np.asarray(x).reshape(1, -1)[(0), :]

VAR_STR = np.asarray(VAR_STR).reshape(1, -1)[(0), :]


sum(sum(i) if isinstance(i, list) else i for i in L)

sum(sum(i) if isinstance(i, list) else i for i in VAR_STR)


Multiple each value by `2` for all keys in a dictionary `my_dict`

my_dict.update((x, y * 2) for x, y in list(my_dict.items()))

VAR_STR.update((x, y * 2) for x, y in list(VAR_STR.items()))


Join elements of list `l` with a comma `,`


make a comma-separated string from a list `myList`


remove substring 'bag,' from a string 'lamp, bag, mirror'

print('lamp, bag, mirror'.replace('bag,', ''))


Reverse the order of words, delimited by `.`, in string `s`


convert epoch time represented as milliseconds `s` to string using format '%Y-%m-%d %H:%M:%S.%f'


parse milliseconds epoch time '1236472051807' to format '%Y-%m-%d %H:%M:%S'


sum elements at index `column` of each list in list `data`

print(sum(row[VAR_STR] for row in VAR_STR))


[sum(row[i] for row in array) for i in range(len(array[0]))]

[sum(row[i] for row in VAR_STR) for i in range(len(VAR_STR[0]))]


combine list of dictionaries `dicts` with the same keys in each list to a single dictionary

dict((k, [d[k] for d in dicts]) for k in dicts[0])

dict((k, [d[k] for d in VAR_STR]) for k in VAR_STR[0])


Merge a nested dictionary `dicts` into a flat dictionary by concatenating nested values with the same key `k`

{k: [d[k] for d in dicts] for k in dicts[0]}

{VAR_STR: [d[VAR_STR] for d in VAR_STR] for VAR_STR in VAR_STR[0]}


How do I get the url parameter in a Flask view


Insert directory 'apps' into directory `__file__`


modify sys.path for python module `subdir`


Insert a 'None' value into a SQLite3 table.

db.execute("INSERT INTO present VALUES('test2', ?, 10)", (None,))


[image for menuitem in list_of_menuitems for image in menuitem]

[image for menuitem in VAR_STR for image in menuitem]


append elements of a set `b` to a list `a`


Append elements of a set to a list in Python


ftp.storlines('STOR ' + filename, open(filename, 'r'))


add one to the hidden web element with id 'XYZ' with selenium python script


create array containing the maximum value of respective elements of array `[2, 3, 4]` and array `[1, 5, 2]`


print a list `l` and move first 3 elements to the end of the list


for fn in os.listdir('.'):
    if os.path.isfile(fn):
        pass

for fn in os.listdir('VAR_STR'):
    if os.path.isfile(fn):
        pass


for (root, dirs, filenames) in os.walk(source):
    for f in filenames:
        pass

for root, dirs, filenames in os.walk(VAR_STR):
    for f in filenames:
        pass


Google App Engine execute GQL query 'SELECT * FROM Schedule WHERE station = $1' with parameter `foo.key()`

db.GqlQuery('SELECT * FROM Schedule WHERE station = $1', foo.key())


filter rows in pandas starting with alphabet 'f' using regular expression.


pandas: delete rows in dataframe `df` based on multiple columns values


format the variables `self.goals` and `self.penalties` using string formatting

"""({:d} goals, ${:d})""".format(self.goals, self.penalties)


format string "({} goals, ${})" with variables `goals` and `penalties`

"""({} goals, ${})""".format(self.goals, self.penalties)


format string "({0.goals} goals, ${0.penalties})"


convert list of lists `L` to list of integers

[int(''.join(str(d) for d in x)) for x in L]

[int(''.join(str(d) for d in x)) for x in VAR_STR]


combine elements of each list in list `L` into digits of a single integer

[''.join(str(d) for d in x) for x in VAR_STR]


convert a list of lists `L` to list of integers

L = [int(''.join([str(y) for y in x])) for x in L]

VAR_STR = [int(''.join([str(y) for y in x])) for x in VAR_STR]


write the elements of list `lines` concatenated by special character '\n' to file `myfile`


removing an element from a list based on a predicate 'X' or 'N'

[x for x in ['AAT', 'XAC', 'ANT', 'TTA'] if 'X' not in x and 'N' not in x]

[x for x in ['AAT', 'XAC', 'ANT', 'TTA'] if 'VAR_STR' not in x and 'VAR_STR' not in
    x]


Remove duplicate words from a string `text` using regex


search for string that matches regular expression pattern '(?<!Distillr)\\\\AcroTray\\.exe' in string 'C:\\SomeDir\\AcroTray.exe'


split string 'QH QD JC KD JS' into a list on white spaces


search for occurrences of regex pattern '>.*<' in xml string `line`


erase all the contents of a file `filename`


convert a string into datetime using the format '%Y-%m-%d %H:%M:%S.%f'


find the index of a list with the first element equal to '332' within the list of lists `thelist`

[index for index, item in enumerate(thelist) if item[0] == '332']

[index for index, item in enumerate(VAR_STR) if item[0] == 'VAR_STR']


subscript text 'H20' with '2' as subscripted in matplotlib labels for arrays 'x' and 'y'.


loop over a list `mylist` if sublists length equals 3


initialize a list `lst` of 100 objects Object()

VAR_STR = [Object() for _ in range(100)]


create list `lst` containing 100 instances of object `Object`

VAR_STR = [VAR_STR() for i in range(100)]


get the content of child tag with`href` attribute whose parent has css `someclass`


joining data from dataframe `df1` with data from dataframe `df2` based on matching values of column 'Date_Time' in both dataframes


use `%s` operator to print variable values `str1` inside a string

'first string is: %s, second one is: %s' % (str1, 'geo.tif')

'first string is: %s, second one is: %s' % (VAR_STR, 'geo.tif')


[x.strip() for x in '2.MATCHES $$TEXT$$ STRING'.split('$$TEXT$$')]


check if directory `directory ` exists and create it if necessary

if (not os.path.exists(directory)):
    os.makedirs(directory)

if not os.path.exists(VAR_STR):
    os.makedirs(VAR_STR)


check if a directory `path` exists and create it if necessary

try:
    os.makedirs(path)
except OSError:
    if (not os.path.isdir(path)):
        raise

try:
    os.makedirs(VAR_STR)
except OSError:
    if not os.VAR_STR.isdir(VAR_STR):
        raise


try:
    os.makedirs(path)
except OSError as exception:
    if (exception.errno != errno.EEXIST):
        raise

try:
    os.makedirs(VAR_STR)
except OSError as exception:
    if exception.errno != errno.EEXIST:
        raise


Replace a separate word 'H3' by 'H1' in a string 'text'


substitute ASCII letters in string 'aas30dsa20' with empty string ''


get digits only from a string `aas30dsa20` using lambda function

"""""".join([x for x in 'aas30dsa20' if x.isdigit()])

"""""".join([x for x in 'VAR_STR' if x.isdigit()])


get a dictionary `records` of key-value pairs in PyMongo cursor `cursor`

records = dict((record['_id'], record) for record in cursor)

VAR_STR = dict((record['_id'], record) for record in VAR_STR)


Create new matrix object  by concatenating data from matrix A and matrix B


concat two matrices `A` and `B` in numpy


find the key associated with the largest value in dictionary `x` whilst key is non-zero value

max(k for k, v in VAR_STR.items() if v != 0)


get the largest key whose not associated with value of 0 in dictionary `x`

(k for k, v in VAR_STR.items() if v != 0)


get the largest key in a dictionary `x` with non-zero value


Update datetime field in `MyModel` to be the existing `timestamp` plus 100 years


merge list `['it']` and list `['was']` and list `['annoying']` into one list


increment a value with leading zeroes in a number `x`


check if a pandas dataframe `df`'s index is sorted


insert data from a string `testfield` to sqlite db `c`

c.execute("INSERT INTO test VALUES (?, 'bar')", (testfield,))

VAR_STR.execute("INSERT INTO test VALUES (?, 'bar')", (VAR_STR,))


decode string "\\x89\\n" into a normal string


convert a raw string `raw_string` into a normal string


convert a raw string `raw_byte_string` into a normal string


split a string `s` with into all strings of repeated characters

[m.group(0) for m in re.finditer('(\\d)\\1*', s)]

[m.group(0) for m in re.finditer('(\\d)\\1*', VAR_STR)]


scatter a plot with x, y position of `np.random.randn(100)` and face color equal to none


plt.plot(np.random.randn(100), np.random.randn(100), 'o', mfc='none')


filter rows containing key word `ball` in column `ids`


convert index at level 0 into a column in dataframe `df`


Add indexes in a data frame `df` to a column `index1`


convert pandas index in a dataframe to columns


Get reverse of list items from list 'b' using extended slicing


convert list `list_of_ints` into a comma separated string

""",""".join([str(i) for i in list_of_ints])


Send a post request with raw data `DATA` and basic authentication with `username` and `password`

requests.post(url, data=DATA, headers=HEADERS_DICT, auth=(username, password))

requests.post(url, data=VAR_STR, headers=HEADERS_DICT, auth=(VAR_STR, VAR_STR))


Iterate ove list `[1, 2, 3]` using list comprehension


extract all the values with keys 'x' and 'y' from a list of dictionaries `d` to list of tuples

[(VAR_STR['VAR_STR'], VAR_STR['VAR_STR']) for VAR_STR in VAR_STR]


get the filename without the extension from file 'hemanth.txt'


create a dictionary by adding each two adjacent elements in tuple `x` as key/value pair to it

dict(x[i:i + 2] for i in range(0, len(x), 2))

dict(VAR_STR[i:i + 2] for i in range(0, len(VAR_STR), 2))


create a list containing flattened list `[['A', 'B', 'C'], ['D', 'E', 'F'], ['G', 'H', 'I']]`


select rows in a dataframe `df` column 'closing_price' between two values 99 and 101

df = df[(df['closing_price'] >= 99) & (df['closing_price'] <= 101)]

VAR_STR = VAR_STR[(VAR_STR['VAR_STR'] >= 99) & (VAR_STR['VAR_STR'] <= 101)]


replace all occurences of newlines `\n` with `<br>` in dataframe `df`


replace all occurrences of a string `\n` by string `<br>` in a pandas data frame `df`


create a list containing each two adjacent letters in string `word` as its elements

[(x + y) for x, y in zip(word, word[1:])]

[(x + y) for x, y in zip(VAR_STR, VAR_STR[1:])]


Get a list of pairs from a string `word` using lambda function

list(map(lambda x, y: x + y, word[:-1], word[1:]))

list(map(lambda x, y: x + y, VAR_STR[:-1], VAR_STR[1:]))


remove all special characters, punctuation and spaces from a string `mystring` using regex


create a DatetimeIndex containing 13 periods of the second friday of each month starting from date '2016-01-01'


Create multidimensional array `matrix` with 3 rows and 2 columns in python


get an absolute file path of file 'mydir/myfile.txt'


split string `my_string` on white spaces


get filename without extension from file `filename`


get a list containing the sum of each element `i` in list `l` plus the previous elements

[sum(VAR_STR[:VAR_STR]) for VAR_STR, _ in enumerate(VAR_STR)]


split a string `Docs/src/Scripts/temp` by `/` keeping `/` in the result


copy all values in a column 'B' to a new column 'D' in a pandas data frame 'df'


find a value within nested json 'data' where the key inside another key 'B' is unknown.


check characters of string `string` are true predication of function `predicate`


convert string `user_input` into a list of integers `user_list`

user_list = [int(number) for number in user_input.split(',')]

VAR_STR = [int(number) for number in VAR_STR.split(',')]


Get a list of integers by splitting  a string `user` with comma


sorted(list, key=lambda x: (x[0], -x[1]))


sort a list of objects `ut`, based on a function `cmpfun` in descending order


reverse list `ut` based on the `count` attribute of each object

ut.sort(key=lambda x: x.count, reverse=True)

VAR_STR.sort(key=lambda x: x.VAR_STR, reverse=True)


sort a list of objects `ut` in reverse order by their `count` property


click a href button 'Send' with selenium


click a href button having text `Send InMail` with selenium


click a href button with text 'Send InMail' with selenium


cast an int `i` to a string and concat to string 'ME'


sort a list `l` by length of value in tuple

l.sort(key=lambda t: len(t[1]), reverse=True)

VAR_STR.sort(key=lambda t: len(t[1]), reverse=True)


split string `s` by words that ends with 'd'


convert elements of each tuple in list `l` into a string  separated by character `@`


convert each tuple in list `l` to a string with '@' separating the tuples' elements


get the html from the current web page of a Selenium driver


Get all matches with regex pattern `\\d+[xX]` in list of string `teststr`

[i for i in teststr if re.search('\\d+[xX]', i)]

[i for i in VAR_STR if re.search('VAR_STR', i)]


select values from column 'A' for which corresponding values in column 'B' will be greater than 50, and in column 'C' - equal 900 in dataframe `df`

VAR_STR['VAR_STR'][(VAR_STR['VAR_STR'] > 50) & (VAR_STR['VAR_STR'] == 900)]


Sort dictionary `o` in ascending order based on its keys and items


How to sort dictionaries by keys in Python


function to convert strings into integers


call a shell script `./test.sh` using subprocess


call a shell script `notepad` using subprocess


combine lists `l1` and `l2`  by alternating their elements

[val for pair in zip(l1, l2) for val in pair]

[val for pair in zip(VAR_STR, VAR_STR) for val in pair]


parse tab-delimited CSV file 'text.txt' into a list

lol = list(csv.reader(open('text.txt', 'rb'), delimiter='\t'))

lol = list(csv.reader(open('VAR_STR', 'rb'), delimiter='\t'))


group a list of dicts `LD` into one dict by key

print(dict(zip(LD[0], zip(*[list(d.values()) for d in LD]))))

print(dict(zip(VAR_STR[0], zip(*[list(d.values()) for d in VAR_STR]))))


How do I sum the first value in each tuple in a list of tuples in Python?

sum([pair[0] for pair in list_of_pairs])


convert unicode string u"{'code1':1,'code2':1}" into dictionary


find all words in a string `mystring` that start with the `$` sign

[word for word in mystring.split() if word.startswith('$')]

[word for word in VAR_STR.split() if word.startswith('VAR_STR')]


text = re.sub('^https?:\\/\\/.*[\\r\\n]*', '', text, flags=re.MULTILINE)

VAR_STR = re.sub('^https?:\\/\\/.*[\\r\\n]*', '', VAR_STR, flags=re.MULTILINE)


running r script '/pathto/MyrScript.r' from python


run r script '/usr/bin/Rscript --vanilla /pathto/MyrScript.r'

subprocess.call('/usr/bin/Rscript --vanilla /pathto/MyrScript.r', shell=True)


replacing nan in the dataframe `df` with row average


Convert unix timestamp '1347517370' to formatted string '%Y-%m-%d %H:%M:%S'


Call a base class's class method `do` from derived class `Derived`


separate words delimited by one or more spaces into a list

re.split(' +', 'hello world sample text')


length of longest element in list `words`


get the value associated with unicode key 'from_user' of first dictionary in list `result`


Retrieve each line from a file 'File.txt' as a list

[line.split() for line in open('File.txt')]

[line.split() for line in open('VAR_STR')]


swap keys with values in a dictionary `a`

res = dict((v, k) for k, v in a.items())

res = dict((v, k) for k, v in VAR_STR.items())


Open a file `path/to/FILE_NAME.ext` in write mode

new_file = open('path/to/FILE_NAME.ext', 'w')


How to count distinct values in a column of a pandas group by object?


Check if any key in the dictionary `dict1` starts with the string `EMP$$`

any(key.startswith('EMP$$') for key in dict1)

any(key.startswith('VAR_STR') for key in VAR_STR)


create list of values from dictionary `dict1` that have a key that starts with 'EMP$$'

[value for key, value in list(dict1.items()) if key.startswith('EMP$$')]

[value for key, value in list(VAR_STR.items()) if key.startswith('VAR_STR')]


print elements of list `list` seperated by tabs `\t`


print unicode string '\xd0\xbf\xd1\x80\xd0\xb8' with utf-8


Encode a latin character in string `Sopet\xc3\xb3n` properly


regex, find "n"s only in the middle of string `s`


display the float `1/3*100` as a percentage


sort a list of dictionary `mylist` by the key `title`


sort a list `l` of dicts by dict value 'title'


sort a list of dictionaries by the value of keys 'title', 'title_url', 'id' in ascending order.

l.sort(key=lambda x: (x['title'], x['title_url'], x['id']))

l.sort(key=lambda x: (x['VAR_STR'], x['VAR_STR'], x['VAR_STR']))


write records in dataframe `df` to table 'test' in schema 'a_schema'


list(dict((x[0], x) for x in L).values())

list(dict((x[0], x) for x in VAR_STR).values())


get the position of item 1 in `testlist`

[i for (i, x) in enumerate(testlist) if (x == 1)]

[i for i, x in enumerate(VAR_STR) if x == 1]


for i in [i for (i, x) in enumerate(testlist) if (x == 1)]:
    pass

for i in [i for i, x in enumerate(VAR_STR) if x == 1]:
    pass


for i in (i for (i, x) in enumerate(testlist) if (x == 1)):
    pass

for i in (i for i, x in enumerate(VAR_STR) if x == 1):
    pass


gen = (i for (i, x) in enumerate(testlist) if (x == 1))
for i in gen:
    pass

gen = (i for i, x in enumerate(VAR_STR) if x == 1)
for i in gen:
    pass


get the position of item `element` in list `testlist`


try:
    print(testlist.index(element))
except ValueError:
    pass

try:
    print(VAR_STR.index(VAR_STR))
except ValueError:
    pass


find the first element of the tuple with the maximum second element in a list of tuples `lis`

max(VAR_STR, key=lambda item: item[1])[0]


get the item at index 0 from the tuple that has maximum value at index 1 in list `lis`


Django set default value of field `b` equal to '0000000'

b = models.CharField(max_length=7, default='0000000', editable=False)

VAR_STR = models.CharField(max_length=7, default='VAR_STR', editable=False)


remove elements from list `oldlist` that have an index number mentioned in list `removelist`

newlist = [v for i, v in enumerate(oldlist) if i not in removelist]

newlist = [v for i, v in enumerate(VAR_STR) if i not in VAR_STR]


Open a file `yourfile.txt` in write mode


convert tuple of tuples `(('aa',), ('bb',), ('cc',))` to tuple

from functools import reduce
reduce(lambda a, b: a + b, (('aa',), ('bb',), ('cc',)))

from functools import reduce
reduce(lambda a, b: a + b, (VAR_STR))


convert tuple of tuples `(('aa',), ('bb',), ('cc',))` to list in one line


Python Pandas: How to replace a characters in a column of a dataframe?


result = ([a for (a, b) in original], [b for (a, b) in original])

result = [a for a, b in VAR_STR], [b for a, b in VAR_STR]


unzip list `original` and return a generator

result = ((a for (a, b) in original), (b for (a, b) in original))

result = (a for a, b in VAR_STR), (b for a, b in VAR_STR)


unzip list `[('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', )]` and fill empty results with None


Add key "mynewkey" to dictionary `d` with value "mynewvalue"


Add key 'a' to dictionary `data` with value 1


Round number `answer` to 2 precision after the decimal point


append each line in file `myfile` into a list

[x for x in myfile.splitlines() if x != '']

[x for x in VAR_STR.splitlines() if x != '']


Get a list of integers `lst` from a file `filename.txt`

lst = map(int, open('filename.txt').readlines())

VAR_STR = map(int, open('VAR_STR').readlines())


generate all 2-element subsets of tuple `(1, 2, 3)`

list(itertools.combinations((1, 2, 3), 2))


Get a new list `list2`by removing empty list from a list of lists `list1`

VAR_STR = [x for x in VAR_STR if x != []]


Create `list2` to contain the lists from list `list1` excluding the empty lists from `list1`


get all text that is not enclosed within square brackets in string `example_str`


Use a regex to get all text in a string `example_str` that is not surrounded by square brackets


get whatever is between parentheses as a single match, and any char outside as an individual match in string '(zyx)bc'


match regex '\\((.*?)\\)|(\\w)' with string '(zyx)bc'


match multiple regex patterns with the alternation operator `|` in a string `(zyx)bc`


formate each string cin list `elements` into pattern '%{0}%'

elements = ['%{0}%'.format(element) for element in elements]

VAR_STR = ['VAR_STR'.format(element) for element in VAR_STR]


get list of values from dictionary 'mydict' w.r.t. list of keys 'mykeys'


convert list `[('Name', 'Joe'), ('Age', 22)]` into a dictionary


average each two columns of array `data`


double backslash escape all double quotes in string `s`


split a string into a list of words and whitespace


plotting stacked barplots on a panda data frame


reverse the keys and values in a dictionary `myDictionary`

{i[1]: i[0] for i in list(myDictionary.items())}

{i[1]: i[0] for i in list(VAR_STR.items())}


for line in mylog:
    list1.append(line)

for line in VAR_STR:
    VAR_STR.append(line)


append a tuple of elements from list `a` with indexes '[0][0] [0][2]' to list `b`


Initialize `SECRET_KEY` in flask config with `Your_secret_string `


find the index of an element 'MSFT' in a list `stocks_list`

[x for x in range(len(stocks_list)) if stocks_list[x] == 'MSFT']

[x for x in range(len(VAR_STR)) if VAR_STR[x] == 'VAR_STR']


Find octal characters matches from a string `str` using regex


split string `input` based on occurrences of regex pattern '[ ](?=[A-Z]+\\b)'


Split string `input` at every space followed by an upper-case letter


send multipart encoded file `files` to url `url` with headers `headers` and metadata `data`

r = requests.post(url, files=files, headers=headers, data=data)

r = requests.post(VAR_STR, VAR_STR=VAR_STR, VAR_STR=VAR_STR, VAR_STR=VAR_STR)


write bytes `bytes_` to a file `filename` in python 3


get a list from a list `lst` with values mapped into a dictionary `dct`


find duplicate names in column 'name' of the dataframe `x`


truncate float 1.923328437452 to 3 decimal places


sort list `li` in descending order based on the date value in second element of each list in list `li`

sorted(li, key=lambda x: datetime.strptime(x[1], '%d/%m/%Y'), reverse=True)

sorted(VAR_STR, key=lambda x: datetime.strptime(x[1], '%d/%m/%Y'), reverse=True)


place the radial ticks in plot `ax` at 135 degrees


check if path `my_path` is an absolute path


pandas dataframe get first row of each group by 'id'


extract attributes 'src="js/([^"]*\\bjquery\\b[^"]*)"' from string `data`


Sum integers contained in strings in list `['', '3.4', '', '', '1.0']`

sum(int(float(item)) for item in [_f for _f in ['', '3.4', '', '', '1.0'] if _f])

sum(int(float(item)) for item in [_f for _f in [VAR_STR] if
    _f])


make a barplot of data in column `group` of dataframe `df` colour-coded according to list `color`


find all matches of regex pattern '([a-fA-F\\d]{32})' in string `data`


remove escape character from string "\\a"


replace each 'a' with 'b' and each 'b' with 'a' in the string 'obama' in a single pass.

"""obama""".replace('a', '%temp%').replace('b', 'a').replace('%temp%', 'b')

"""VAR_STR""".replace('VAR_STR', '%temp%').replace('VAR_STR', 'VAR_STR').replace(
    '%temp%', 'VAR_STR')


create a new column `weekday` in pandas data frame `data` based on the values in column `my_dt`

data['weekday'] = data['my_dt'].apply(lambda x: x.weekday())

VAR_STR['VAR_STR'] = VAR_STR['VAR_STR'].apply(lambda x: x.VAR_STR())


sorted(list(x.items()), key=lambda pair: pair[1], reverse=True)

sorted(list(VAR_STR.items()), key=lambda pair: pair[1], reverse=True)


append a numpy array 'b' to a numpy array 'a'


fetch address information for host 'google.com' ion port 80


add a column 'day' with value 'sat' to dataframe `df`


Flask set folder 'wherever' as the default template folder


How do I INSERT INTO t1 (SELECT * FROM t2) in SQLAlchemy?

session.execute('INSERT INTO t1 (SELECT * FROM t2)')


sort a list of lists 'c2' such that third row comes first


c2.sort(key=lambda row: (row[2], row[1], row[0]))


c2.sort(key=lambda row: (row[2], row[1]))


set font `Arial` to display non-ascii characters in matplotlib

matplotlib.rc('font', **{'sans-serif': 'Arial', 'family': 'sans-serif'})

matplotlib.rc('font', **{'sans-serif': 'VAR_STR', 'family': 'sans-serif'})


Convert  DateTime column 'date' of pandas dataframe 'df' to ordinal


get html source of Selenium WebElement `element`


open a 'gnome' terminal from python script and run  'sudo apt-get update' command.

os.system('gnome-terminal -e \'bash -c "sudo apt-get update; exec bash"\'')


add an item with key 'third_key' and value 1 to an dictionary `my_dict`


add an entry 'wuggah' at the beginning of list `myList`


convert a hex-string representation to actual bytes


select the last column of dataframe `df`


get the first value from dataframe `df` where column 'Letters' is equal to 'C'

df.loc[df['Letters'] == 'C', 'Letters'].values[0]

VAR_STR.loc[VAR_STR['VAR_STR'] == 'VAR_STR', 'VAR_STR'].values[0]


get the type of variable `variable_name`


next(itertools.islice(range(10), 5, 5 + 1))


Print a string `word` with string format


join a list of strings `list` using a space ' '


create list `y` containing two empty lists


read a file 'C:/name/MyDocuments/numbers' into a list `data`

data = [line.strip() for line in open('C:/name/MyDocuments/numbers', 'r')]

VAR_STR = [line.strip() for line in open('VAR_STR', 'r')]


Drop rows of pandas dataframe `df` having NaN in column at index "1"


get elements from list `myList`, that have a field `n` value 30


round off the float that is the product of `2.52 * 100` and convert it to an int


loop through the IP address range "192.168.x.x"

for i in range(256):
    for j in range(256):
        ip = ('192.168.%d.%d' % (i, j))
        print(ip)

for i in range(256):
    for j in range(256):
        ip = '192.168.%d.%d' % (i, j)
        print(ip)


for (i, j) in product(list(range(256)), list(range(256))):
    pass

for i, j in product(list(range(256)), list(range(256))):
    pass


Sum the corresponding decimal values for binary values of each boolean element in list `x`

sum(1 << i for i, b in enumerate(x) if b)

sum(1 << i for i, b in enumerate(VAR_STR) if b)


write multiple strings `line1`, `line2` and `line3` in one line in a file `target`

target.write('%r\n%r\n%r\n' % (line1, line2, line3))

VAR_STR.write('%r\n%r\n%r\n' % (VAR_STR, VAR_STR, VAR_STR))


Convert list of lists `data` into a flat list

[y for x in data for y in (x if isinstance(x, list) else [x])]

[y for x in VAR_STR for y in (x if isinstance(x, list) else [x])]


Print new line character as `\n` in a string `foo\nbar`


remove last comma character ',' in string `s`


calculate the mean of each element in array `x` with the element previous to it


get an array of the mean of each two consecutive values in numpy array `x`


load data containing `utf-8` from file `new.txt` into numpy array `arr`

arr = numpy.fromiter(codecs.open('new.txt', encoding='utf-8'), dtype='<U2')

VAR_STR = numpy.fromiter(codecs.open('VAR_STR', encoding='VAR_STR'), dtype='<U2')


reverse sort list of dicts `l` by value for key `time`

l = sorted(l, key=itemgetter('time'), reverse=True)

VAR_STR = sorted(VAR_STR, key=itemgetter('VAR_STR'), reverse=True)


Sort a list of dictionary `l` based on key `time` in descending order

l = sorted(l, key=lambda a: a['time'], reverse=True)

VAR_STR = sorted(VAR_STR, key=lambda a: a['VAR_STR'], reverse=True)


get rows of dataframe `df` that match regex '(Hel|Just)'


find the string in `your_string` between two special characters "[" and "]"


How to create a list of date string in 'yyyymmdd' format with Python Pandas?


count number of times string 'brown' occurred in string 'The big brown fox is brown'

"""The big brown fox is brown""".count('brown')


download the file from url `url` and save it under file `file_name`


Split string `line` into a list by whitespace


replace dot characters  '.' associated with ascii letters in list `s` with space ' '


sort list `list_of_strings` based on second index of each string `s`

sorted(list_of_strings, key=lambda s: s.split(',')[1])

sorted(VAR_STR, key=lambda VAR_STR: VAR_STR.split(',')[1])


call multiple bash function ‘vasp’ and ‘tee tee_output’ using ‘|’

subprocess.check_call('vasp | tee tee_output', shell=True)


[element for element in lst if isinstance(element, int)]

[element for element in VAR_STR if isinstance(element, int)]


get all the elements except strings from the list 'lst'.

[element for element in lst if not isinstance(element, str)]

[element for element in VAR_STR if not isinstance(element, str)]


Sort a list of dictionaries `list_to_be_sorted` by the value of the dictionary key `name`

newlist = sorted(list_to_be_sorted, key=lambda k: k['name'])

newlist = sorted(VAR_STR, key=lambda k: k['VAR_STR'])


sort a list of dictionaries `l` by values in key `name` in descending order

newlist = sorted(l, key=itemgetter('name'), reverse=True)

newlist = sorted(VAR_STR, key=itemgetter('VAR_STR'), reverse=True)


How do I sort a list of dictionaries by values of the dictionary in Python?


join together with "," elements inside a list indexed with 'category' within a dictionary `trans`


concatenate array of strings `['A', 'B', 'C', 'D']` into a string


Remove all strings from a list a strings `sents` where the values starts with `@$\t` or `#`

[x for x in sents if not x.startswith('@$\t') and not x.startswith('#')]

[x for x in VAR_STR if not x.startswith('VAR_STR') and not x.startswith('VAR_STR')]


convert datetime object `(1970, 1, 1)` to seconds

(t - datetime.datetime(1970, 1, 1)).total_seconds()


insert `_suff` before the file extension in `long.file.name.jpg` or replace `_a` with `suff` if it precedes the extension.


convert int values in list `numlist` to float


Create a list containing all ascii characters as its elements


python regex - check for a capital letter with a following lowercase in string `string`


f = open('myfile', 'w')
f.write('hi there\n')
f.close()

f = open('VAR_STR', 'w')
f.write('hi there\n')
f.close()


write line "Hello" to file `somefile.txt`

with open('somefile.txt', 'a') as the_file:
    the_file.write('Hello\n')

with open('VAR_STR', 'a') as the_file:
    the_file.write('Hello\n')


Find all numbers and dots from a string `text` using regex


python regex  to find all numbers and dots from 'text'


execute script 'script.ps1' using 'powershell.exe' shell


Sort a list of tuples `b` by third item in the tuple


get a list of all keys in Cassandra database `cf` with pycassa


get the index of an integer `1` from a list `lst` if the list also contains boolean items

next(i for i, x in enumerate(lst) if not isinstance(x, bool) and x == 1)

next(i for i, x in enumerate(VAR_STR) if not isinstance(x, bool) and x == 1)


subtract 13 from every number in a list `a`

VAR_STR[:] = [(x - 13) for x in VAR_STR]


choose a random file from the directory contents of the C drive, `C:\\`


re.findall('"(http.*?)"', s, re.MULTILINE | re.DOTALL)

re.findall('"(http.*?)"', VAR_STR, re.MULTILINE | re.DOTALL)


match urls whose domain doesn't start with `t` from string `document` using regex


split a string `mystring` considering the spaces ' '


sum elements at the same index in list `data`

[[sum(item) for item in zip(*items)] for items in zip(*data)]

[[sum(item) for item in zip(*items)] for items in zip(*VAR_STR)]