Use python list IN postgresql query
<p>My question is very similar to <a href="http://stackoverflow.com/questions/283645/python-list-in-sql-query-as-parameter">this</a> but I have strings instead of integers in my list.</p>

<p>My <code>python list</code>:<br></p>

<pre><code>list = ['a', 'b'] #number of items varies from 1 to 6
</code></pre>

<p>I want to use this list in Postgres query like this</p>

<pre><code>select * from sample where sub in ('a', 'b');
</code></pre>

<p>I can use <code>tuple(list)</code> to get <code>('a', 'b')</code>, this is not useful when length of my list became one. I am struggling to find a way to convert<br><br>
<code>['a']</code> to <code>('a')</code> <br>
<code>['a', 'b']</code> to <code>('a', 'b')</code><br><br>
I tried </p>

<pre><code>In[91]: myquery = "select * from sample where sub in (%s)" % ",".join(map(str,list))
In[92]: myquery
Out[92]: 'select * from sample where sub in (a,b,c)'
</code></pre>

<p>But postgres expects</p>

<pre><code>select * from sample where sub in ('a', 'b');
</code></pre>

<p>I haven't used python's bindings to postgresql so I don't know if it is possible to bind a python list (or a tuple) to a placeholder in a query, but if it is, then you could use the <code>ANY</code> operator as follows:</p>

<pre><code>SELECT * FROM sample WHERE sub = ANY (%s);
</code></pre>

<p>and bind the list the only parameter.</p>

python postgresql