neulab/docprompting-conala huggingface dataset:
# Get a string with string formatting from dictionary `d`
""", """.join(['{}_{}'.format(k, v) for k, v in d.items()])
# get the ASCII value of a character u'あ' as an int
ord('\u3042')
# What's the best way to search for a Python dictionary value in a list of dictionaries?
any(d['site'] == 'Superuser' for d in data)
# separate numbers from characters in string "30m1000n20m"
re.findall('(([0-9]+)([A-Z]))', '20M10000N80M')
# separate numbers and characters in string '20M10000N80M'
re.findall('([0-9]+|[A-Z])', '20M10000N80M')
# separate numbers and characters in string '20M10000N80M'
re.findall('([0-9]+)([A-Z])', '20M10000N80M')
# manually throw/raise a `ValueError` exception with the message 'A very specific bad thing happened'
raise ValueError('A very specific bad thing happened')
# throw a ValueError with message 'represents a hidden bug, do not catch this'
raise ValueError('represents a hidden bug, do not catch this')
# throw an Exception with message 'This is the exception you expect to handle'
raise Exception('This is the exception you expect to handle')
# throw a value error with message 'A very specific bad thing happened', 'foo', 'bar', 'baz'
raise ValueError('A very specific bad thing happened')
# throw an assertion error with message "Unexpected value of 'distance'!", distance
raise AssertionError("Unexpected value of 'distance'!", distance)
# get unique values from the list `['a', 'b', 'c', 'd']`
set(['a', 'b', 'c', 'd'])
# split string `s` based on white spaces
re.findall('\\s+|\\S+', s)
# convert a hex string `x` to string
y = str(int(x, 16))
# get list of duplicated elements in range of 3
[y for x in range(3) for y in [x, x]]
# remove elements in list `b` from list `a`
[x for x in a if x not in b]
# create a list `matrix` containing 5 lists, each of 5 items  all set to 0
matrix = [([0] * 5) for i in range(5)]
# interleave the elements of two lists `a` and `b`
[j for i in zip(a, b) for j in i]
# merge two lists `a` and `b` into a single list
[j for i in zip(a, b) for j in i]
# SQLite get a list of column names from cursor object `cursor`
names = list(map(lambda x: x[0], cursor.description))
# select the last business day of the month for each month in 2014 in pandas
pd.date_range('1/1/2014', periods=12, freq='BM')
# rename `last` row index label in dataframe `df` to `a`
df = df.rename(index={last: 'a'})
# Finding the largest delta between two integers in a list in python
max(abs(x - y) for x, y in zip(values[1:], values[:-1]))
# pads string '5' on the left with 1 zero
print('{0}'.format('5'.zfill(2)))
# Unzip a list of tuples `l` into a list of lists
zip(*l)
# reduce the first element of list of strings `data` to a string, separated by '.'
print('.'.join([item[0] for item in data]))
# get the first element of each tuple from a list of tuples `G`
[x[0] for x in G]
# create list `changed_list ` containing elements of list `original_list` whilst converting strings containing digits to integers
changed_list = [(int(f) if f.isdigit() else f) for f in original_list]
# regular expression syntax for not to match anything
re.compile('.\\A|.\\A*|.\\A+')
# create a regular expression object with a pattern that will match nothing
re.compile('a^')
# convert a list of strings `lst` to list of integers
[map(int, sublist) for sublist in lst]
# convert strings in list-of-lists `lst` to ints
[[int(x) for x in sublist] for sublist in lst]
# create a list with the characters of a string `5+6`
list('5+6')
# How to download a file via FTP with Python ftplib
ftp.retrbinary('RETR %s' % filename, file.write)
# print the number of occurences of not `none` in a list `lst` in Python 2
print(len([x for x in lst if x is not None]))
# get a sum of 4d array `M`
M.sum(axis=0).sum(axis=0)
# sort a python dictionary `a_dict` by element `1` of the value
sorted(list(a_dict.items()), key=lambda item: item[1][1])
# delete an item `thing` in a list `some_list` if it exists
cleaned_list = [x for x in some_list if x is not thing]
# get the number of all keys in the nested dictionary `dict_list`
len(dict_test) + sum(len(v) for v in dict_test.values())
# find the sums of length 7 subsets of a list `daily`
weekly = [sum(visitors[x:x + 7]) for x in range(0, len(daily), 7)]
# Get a list of all keys from dictionary `dictA` where the number of occurrences of value `duck` in that key is more than `1`
[k for k, v in dictA.items() if v.count('duck') > 1]
# generate a list of consecutive integers from 0 to 8
list(range(9))
# getting every possible combination of two elements in a list
list(itertools.combinations([1, 2, 3, 4, 5, 6], 2))
# split string 'x+13.5*10x-4e1' into tokens
print([i for i in re.split('([\\d.]+|\\W+)', 'x+13.5*10x-4e1') if i])
# unpack elements of list `i` as arguments into function `foo`
foo(*i)
# remove all square brackets from string 'abcd[e]yth[ac]ytwec'
re.sub('\\[.*?\\]', '', 'abcd[e]yth[ac]ytwec')
# set dataframe `df` index using column 'month'
df.set_index('month')
# get a list of the row names from index of a pandas data frame
list(df.index)
# filtering out strings that contain 'ab' from a list of strings `lst`
[k for k in lst if 'ab' in k]
# From a list of strings `my_list`, remove the values that contains numbers.
[x for x in my_list if not any(c.isdigit() for c in x)]
# get file '~/foo.ini'
config_file = os.path.expanduser('~/foo.ini')
# split string `text` into chunks of 16 characters each
re.findall('.{,16}\\b', text)
# remove line breaks from string `textblock` using regex
re.sub('(?<=[a-z])\\r?\\n', ' ', textblock)
# convert scientific notation of variable `a` to decimal
"""{:.50f}""".format(float(a[0] / a[1]))
# create a list containing the indices of elements greater than 4 in list `a`
[i for i, v in enumerate(a) if v > 4]
# split 1d array `a` into 2d array at the last element
np.split(a, [-1])
# convert dataframe `df` to list of dictionaries including the index values
df.to_dict('index')
# Create list of dictionaries from pandas dataframe `df`
df.to_dict('records')
# convert list `x` into a flat list
y = map(operator.itemgetter(0), x)
# get a list `y` of the first element of every tuple in list `x`
y = [i[0] for i in x]
# Group a pandas data frame by monthly frequenct `M` using groupby
df.groupby(pd.TimeGrouper(freq='M'))
# Find average of a nested list `a`
a = [(sum(x) / len(x)) for x in zip(*a)]
# Get the age of directory (or file) `/tmp` in seconds.
print(os.path.getmtime('/tmp'))
# Convert string to boolean from defined set of strings
s in ['true', '1', 't', 'y', 'yes', 'yeah', 'yup', 'certainly', 'uh-huh']
# Format string `hello {name}, how are you {name}, welcome {name}` to be interspersed by `name` three times, specifying the value as `john` only once
"""hello {name}, how are you {name}, welcome {name}""".format(name='john')
# divide the members of a list `conversions` by the corresponding members of another list `trials`
[(c / t) for c, t in zip(conversions, trials)]
# searche in HTML string for elements that have text 'Python'
soup.body.findAll(text='Python')
# BeautifulSoup find string 'Python Jobs' in HTML body `body`
soup.body.findAll(text='Python Jobs')
# Initialize a list `a` with `10000` items and each item's value `0`
a = [0] * 10000
# Sort lists in the list `unsorted_list` by the element at index 3 of each list
unsorted_list.sort(key=lambda x: x[3])
# Replace NaN values in  column 'value' with the mean of data in column 'group' of dataframe `df`
df[['value']].fillna(df.groupby('group').transform('mean'))
# add a path `/path/to/2014_07_13_test` to system path
sys.path.append('/path/to/2014_07_13_test')
# remove None value from list `L`
[x for x in L if x is not None]
# Split string with comma (,) and remove whitespace from a string 'my_string'
[item.strip() for item in my_string.split(',')]
# get current script directory
os.path.dirname(os.path.abspath(__file__))
# Match regex pattern '((?:A|B|C)D)' on string 'BDE'
re.findall('((?:A|B|C)D)', 'BDE')
# create list `done` containing permutations of each element in list `[a, b, c, d]` with variable `x` as tuples
done = [(el, x) for el in [a, b, c, d]]
# How do I find an element that contains specific text in Selenium Webdriver (Python)?
driver.find_elements_by_xpath("//*[contains(text(), 'My Button')]")
# Selecting Element "//li/label/input" followed by text "polishpottery" with Selenium WebDriver `driver`
driver.find_element_by_xpath("//li/label/input[contains(..,'polishpottery')]")
# Resample dataframe `frame` to resolution of 1 hour `1H` for timeseries index, summing values in the column `radiation` averaging those in column `tamb`
frame.resample('1H').agg({'radiation': np.sum, 'tamb': np.mean})
# sum each element `x` in list `first` with element `y` at the same index in list `second`.
[(x + y) for x, y in zip(first, second)]
# get the context of a search by keyword 'My keywords' in beautifulsoup `soup`
k = soup.find(text=re.compile('My keywords')).parent.text
# sort list `xs` based on the length of its elements
print(sorted(xs, key=len))
# sort list `xs` in ascending order of length of elements
xs.sort(lambda x, y: cmp(len(x), len(y)))
# sort list of strings `xs` by the length of string
xs.sort(key=lambda s: len(s))
# Make a dictionary from list `f` which is in the format of four sets of  "val, key, val"
{f[i + 1]: [f[i], f[i + 2]] for i in range(0, len(f), 3)}
# Check if string `strg` starts with any of the elements in list ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9')
strg.startswith(('0', '1', '2', '3', '4', '5', '6', '7', '8', '9'))
# create a list containing all values associated with key 'baz' in dictionaries of list `foos` using list comprehension
[y['baz'] for x in foos for y in x['bar']]
# Make a auto scrolled window to the end of the list in gtk
self.treeview.connect('size-allocate', self.treeview_changed)
# Getting today's date in YYYY-MM-DD
datetime.datetime.today().strftime('%Y-%m-%d')
# creating a list of dictionaries [{'A': 1, 'C': 4, 'B': 2, 'D': 4}, {'A': 1, 'C': 4, 'B': 1, 'D': 5}]
A: 1
C: 4
B: 2
D: 4
A: 1
C: 4
B: 1
D: 5
# Creating a list of dictionaries in python
A: 1
C: 4
B: 2
D: 4
A: 1
C: 4
B: 1
D: 5
# print variable `value ` without spaces
print('Value is "' + str(value) + '"')
# Print a string `value` with string formatting
print('Value is "{}"'.format(value))
# get index of the biggest 2 values of a list `a`
sorted(list(range(len(a))), key=lambda i: a[i])[-2:]
# get indexes of the largest `2` values from a list `a` using itemgetter
zip(*sorted(enumerate(a), key=operator.itemgetter(1)))[0][-2:]
# get the indexes of the largest `2` values from a list of integers `a`
sorted(list(range(len(a))), key=lambda i: a[i], reverse=True)[:2]
# adding url `url` to mysql row
cursor.execute('INSERT INTO index(url) VALUES(%s)', (url,))
# fill list `myList` with 4 0's
self.myList.extend([0] * (4 - len(self.myList)))
# immediately see output of print statement that doesn't end in a newline
sys.stdout.flush()
# check if all values of a dictionary `your_dict` are zero `0`
all(value == 0 for value in list(your_dict.values()))
# count number of occurrences of a substring 'ab' in a string "abcdabcva"
"""abcdabcva""".count('ab')
# get the union set from list of lists `results_list`
results_union = set().union(*results_list)
# get the union of values in list of lists `result_list`
return list(set(itertools.chain(*result_list)))
# make a flat list from list of lists `sublist`
[item for sublist in l for item in sublist]
# make a flat list from list of lists `list2d`
list(itertools.chain(*list2d))
# make a flat list from list of lists `list2d`
list(itertools.chain.from_iterable(list2d))
# join two dataframes based on values in selected columns
pd.merge(a, b, on=['A', 'B'], how='outer')
# get all the values in column `b` from pandas data frame `df`
df['b']
# convert Date object `dateobject` into a DateTime object
datetime.datetime.combine(dateobject, datetime.time())
# How to exclude a character from a regex group?
re.compile('[^a-zA-Z0-9-]+')
# remove Nan values from array `x`
x = x[numpy.logical_not(numpy.isnan(x))]
# index a list `L` with another list `Idx`
T = [L[i] for i in Idx]
# How to plot two columns of a pandas data frame using points?
df.plot(x='col_name_1', y='col_name_2', style='o')
# remove all non-numeric characters from string `sdkjh987978asd098as0980a98sd `
re.sub('[^0-9]', '', 'sdkjh987978asd098as0980a98sd')
# finding the index of an item 'foo' given a list `['foo', 'bar', 'baz']` containing it
[i for i, j in enumerate(['foo', 'bar', 'baz']) if j == 'foo']
# Validate IP address using Regex
pat = re.compile('^\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$')
# subtract elements of list `List1` from elements of list `List2`
[(x1 - x2) for x1, x2 in zip(List1, List2)]
# extract date from a string 'monkey 2010-07-32 love banana'
dparser.parse('monkey 2010-07-32 love banana', fuzzy=True)
# extract date from a string 'monkey 20/01/1980 love banana'
dparser.parse('monkey 20/01/1980 love banana', fuzzy=True)
# extract date from a string `monkey 10/01/1980 love banana`
dparser.parse('monkey 10/01/1980 love banana', fuzzy=True)
# remove a key 'key' from a dictionary `my_dict`
my_dict.pop('key', None)
# sort list `a` in ascending order based on its elements' float values
a = sorted(a, key=lambda x: float(x))
# Sort list `alist` in ascending order based on each of its elements' attribute `foo`
alist.sort(key=lambda x: x.foo)
# open file '5_1.txt' in directory `direct`
x_file = open(os.path.join(direct, '5_1.txt'), 'r')
# save numpy array `x` into text file 'test.txt'
np.savetxt('test.txt', x)
# get the list with the highest sum value in list `x`
print(max(x, key=sum))
# get the value at index 1 for each tuple in the list of tuples `L`
[x[1] for x in L]
# create a set that is the exclusive or of [1, 2, 3] and [3, 4, 5]
set([1, 2, 3]) ^ set([3, 4, 5])
# if Selenium textarea element `foo` is not empty, clear the field
driver.find_element_by_id('foo').clear()
# clear text from textarea 'foo' with selenium
driver.find_element_by_id('foo').clear()
# make a function `f` that calculates the sum of two integer variables `x` and `y`
f = lambda x, y: x + y
# 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
df.apply(lambda x: x.tolist(), axis=1)
# split a unicode string `text` into a list of words and punctuation characters with a regex
re.findall('\\w+|[^\\w\\s]', text, re.UNICODE)
# sum all the values in a counter variable `my_counter`
sum(my_counter.values())
# convert 3652458 to string represent a 32bit hex number
"""0x{0:08X}""".format(3652458)
# print two numbers `10` and `20` using string formatting
"""{0} {1}""".format(10, 20)
# replace placeholders in string '{1} {ham} {0} {foo} {1}' with arguments `(10, 20, foo='bar', ham='spam')`
"""{1} {ham} {0} {foo} {1}""".format(10, 20, foo='bar', ham='spam')
# insert string `string1` after each character of `string2`
string2.replace('', string1)[len(string1):-len(string1)]
# check whether elements in list `a` appear only once
len(set(a)) == len(a)
# take screenshot 'screen.png' on mac os x
os.system('screencapture screen.png')
# sort pandas data frame `df` using values from columns `c1` and `c2` in ascending order
df.sort(['c1', 'c2'], 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([1, 2, 3], [4, 5, 6], [7, 8, 9])]
# modify the width of a text control as `300` keeping default height in wxpython
wx.TextCtrl(self, -1, size=(300, -1))
# erase the contents of a file `filename`
open('filename', 'w').close()
# How to erase the file contents of text file in Python?
open('file.txt', 'w').close()
# Create sub matrix of a list of lists `[[2, 3, 4], [2, 3, 4], [2, 3, 4]]` (without numpy)
[[2, 3, 4], [2, 3, 4], [2, 3, 4]]
# sort each row in a pandas dataframe `df` in descending order
df.sort(axis=1, ascending=False)
# Fastest way to sort each row in a pandas dataframe
df.sort(df.columns, axis=1, ascending=False)
# delete all rows in a numpy array `a` where any value in a row is zero `0`
a[np.all(a != 0, axis=1)]
# sort array `order_array` based on column 'year', 'month' and 'day'
order_array.sort(order=['year', 'month', 'day'])
# Sort a structured numpy array 'df' on multiple columns 'year', 'month' and 'day'.
df.sort(['year', 'month', 'day'])
# remove multiple values from a list `my_list` at the same time with index starting at `2` and ending just before `6`.
del my_list[2:6]
# pandas read comma-separated CSV file `s` and skip commented lines starting with '#'
pd.read_csv(StringIO(s), sep=',', comment='#')
# get a name of function `my_function` as a string
my_function.__name__
# get a random record from model 'MyModel' using django's orm
MyModel.objects.order_by('?').first()
# in Django, select 100 random records from the database `Content.objects`
Content.objects.all().order_by('?')[:100]
# Merge all columns in dataframe `df` into one column
df.apply(' '.join, axis=0)
# write a tuple of tuples `A` to a csv file using python
writer.writerow(A)
# Write all tuple of tuples `A` at once into csv file
writer.writerows(A)
# split string `s` to list conversion by ','
[x.strip() for x in s.split(',')]
# delete all elements from a list `x` if a function `fn` taking value as parameter returns `0`
[x for x in lst if fn(x) != 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))
# 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)}
# Python regular expression match whole word
re.search('\\bis\\b', your_string)
# Set the resolution of a monitor as `FULLSCREEN` in pygame
pygame.display.set_mode((0, 0), pygame.FULLSCREEN)
# find button that is in li class `next` and assign it to variable `next`
next = driver.find_element_by_css_selector('li.next>a')
# 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.
fh1.seek(2)
# Get the value of the minimum element in the second column of array `a`
a[np.argmin(a[:, (1)])]
# create a list containing elements of list `a` if the sum of the element is greater than 10
[item for item in a if sum(item) > 10]
# to convert a list of tuples `list_of_tuples` into list of lists
[list(t) for t in zip(*list_of_tuples)]
# group a list `list_of_tuples` of tuples by values
zip(*list_of_tuples)
# Add 1 to each integer value in list `my_list`
new_list = [(x + 1) for x in my_list]
# Strip punctuation from string `s`
s.translate(None, string.punctuation)
# remove the last dot and all text beyond it in string `s`
re.sub('\\.[^.]+$', '', s)
# merge lists `list_a` and `list_b` into a list of tuples
zip(list_a, list_b)
# merge lists `a` and `a` into a list of tuples
list(zip(a, b))
# How to select element with Selenium Python xpath
driver.find_element_by_xpath("//div[@id='a']//a[@class='click']")
# apply `numpy.linalg.norm` to each row of a matrix `a`
numpy.apply_along_axis(numpy.linalg.norm, 1, a)
# append dict `{'f': var6, 'g': var7, 'h': var8}` to value of key `e` in dict `jsobj['a']['b']`
jsobj['a']['b']['e'].append({'f': var6, 'g': var7, 'h': var8})
# read json `elevations` to pandas dataframe `df`
pd.read_json(elevations)
# keep a list `dataList` of lists sorted as it is created by second element
dataList.sort(key=lambda x: x[1])
# sorting a list of tuples `list_of_tuples` where each tuple is reversed
sorted(list_of_tuples, 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)
# check if string 'x' is  in list `['x', 'd', 'a', 's', 'd', 's']`
'x' in ['x', 'd', 'a', 's', 'd', 's']
# Get the first and last 3 elements of list `l`
l[:3] + l[-3:]
# remove a substring ".com" from the end of string `url`
if url.endswith('.com'):
    url = url[:(-4)]
# remove a substring ".com" from the end of string `url`
url = re.sub('\\.com$', '', url)
# remove a substring ".com" from the end of string `url`
print(url.replace('.com', ''))
# remove a substring `suffix` from the end of string `text`
if (not text.endswith(suffix)):
    return text
return text[:(len(text) - len(suffix))]
# find the euclidean distance between two 3-d arrays `A` and `B`
np.sqrt(((A - B) ** 2).sum(-1))
# split string `a` using new-line character '\n' as separator
a.rstrip().split('\n')
# split a string `a` with new line character
a.split('\n')[:-1]
# unpack the arguments out of list `params` to function `some_func`
some_func(*params)
# python regex for hyphenated words in `text`
re.findall('\\w+(?:-\\w+)+', text)
# plot a bar graph from the column 'color' in the DataFrame 'df'
df.colour.value_counts().plot(kind='bar')
# plot categorical data in series `df` with kind `bar` using pandas and matplotlib
df.groupby('colour').size().plot(kind='bar')
# 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
"""Name: {0[person.name]}""".format({'person.name': 'Joe'})
# open the file 'words.txt' in 'rU' mode
f = open('words.txt', 'rU')
# Replace each value in column 'prod_type' of dataframe `df` with string 'responsive'
df['prod_type'] = 'responsive'
# python get time stamp on file `file` in '%m/%d/%Y' format
time.strftime('%m/%d/%Y', time.gmtime(os.path.getmtime(file)))
# duplicate data in pandas dataframe `x` for 5 times
pd.concat([x] * 5, ignore_index=True)
# Get a repeated pandas data frame object `x` by `5` times
pd.concat([x] * 5)
# kill a process `make.exe` from python script on windows
os.system('taskkill /im make.exe')
# check if all elements in list `mylist` are the same
len(set(mylist)) == 1
# find recurring patterns in a string '42344343434'
re.findall('^(.+?)((.+)\\3+)$', '42344343434')[0][:-1]
# 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`
dict(zip(x, y))
# get full path of current directory
os.path.dirname(os.path.abspath(__file__))
# generate a list from a pandas dataframe `df` with the column name and column values
df.values.tolist()
# check if all lists in list `L` have three elements of integer 1
all(x.count(1) == 3 for x in L)
# Sort list `my_list` in alphabetical order based on the values associated with key 'name' of each dictionary in the list
my_list.sort(key=operator.itemgetter('name'))
# display first 5 characters of string 'aaabbbccc'
"""{:.5}""".format('aaabbbccc')
# Convert a list `['A:1', 'B:2', 'C:3', 'D:4']` to dictionary
dict(map(lambda s: s.split(':'), ['A:1', 'B:2', 'C:3', 'D:4']))
# recursively go through all subdirectories and files in `rootdir`
for (root, subFolders, files) in os.walk(rootdir):
    pass
# sort list `X` based on values from another list `Y`
[x for y, x in sorted(zip(Y, X))]
# sorting list 'X' based on values from another list 'Y'
[x for y, x in sorted(zip(Y, X))]
# remove parentheses and text within it in string `filename`
re.sub('\\([^)]*\\)', '', filename)
# find all `owl:Class` tags by parsing xml with namespace
root.findall('{http://www.w3.org/2002/07/owl#}Class')
# Concatenate dataframe `df_1` to dataframe `df_2` sorted by values of the column 'y'
pd.concat([df_1, df_2.sort_values('y')])
# sum values greater than 0 in dictionary `d`
sum(v for v in list(d.values()) if v > 0)
# Get all the items from a list of tuple 'l' where second item in tuple is '1'.
[x for x in l if x[1] == 1]
# generate list of numbers in specific format using string formatting precision.
[('%.2d' % i) for i in range(16)]
# strip everything up to and including the character `&` from url `url`, strip the character `=` from the remaining string and concatenate `.html` to the end
url.split('&')[-1].replace('=', '') + '.html'
# select a random element from array `[1, 2, 3]`
random.choice([1, 2, 3])
# remove all non-alphabet chars from string `s`
"""""".join([i for i in s if i.isalpha()])