give parameter(list or array) to in operator - python, sql

The idea is to have a query like this one:

cursor.execute("SELECT ... IN (%s, %s, %s)", (1, 2, 3))

where each %s will be substituted by elements in your list. To construct this string query you can do:

placeholders= ', '.join(['%s']*len(article_ids))  # "%s, %s, %s, ... %s"
query = 'SELECT name FROM table WHERE article_id IN ({})'.format(placeholders)

finally

cursor.execute(query, tuple(article_ids))

For Python3 you can use

article_ids = [1,2,3,4,5,6]
sql_list = str(tuple([key for key in article_ids])).replace(',)', ')')
query ="""
    SELECT id FROM table WHERE article_id IN {sql_list}
""".format(sql_list=sql_list)

resulting in

>>> print(query)

    SELECT id FROM table WHERE article_id IN (1, 2, 3, 4, 5, 6)

which you can feed to

cursor.execute(query)

This also works for article_ids of only 1 value (where tuple generates (1,)).

It also works for arrays of strings:

article_titles = ['some', 'article titles']

resulting in

    SELECT id FROM table WHERE article_title IN ('some', 'article titles')