Python list - string formatting as list indices
<p>Depending on a condition I need to get a value from one or another function. I'm trying to put it inside a simple <code>If ... Else</code> statement. I tried to use <code>%s</code> string formatting but it won't work. Below code, so it will become more clear what I try to do:</p>

<pre><code>if condition:
    item = my_list['%s']
else:
    item = my_other_list['%s']

# now I do something with this value:
print item % 3
</code></pre>

<p>This way I tried to <code>print</code> 3rd value of one or other list if the <code>condition</code> was True of False. This returned an error about list indices being string. So I tried to put it inside <code>int()</code> what didn't help. </p>

<p>How should I do it? The problem is I get the value <strong>later</strong> than I declare what <code>item</code> is.</p>

<p><strong>EDIT</strong>
I will add some more infos here:</p>

<p>I have a <code>for</code> loop, that goes through ~1000 elements and processes them. If the <code>condition</code> is <code>True</code>, it calls one function or another if false. Now, I don't want to check the same condition 1000 times, because I know it won't change during the time and would like to check it once and apply the method to all of the elements. </p>

<p>More code:</p>

<pre><code>if self.dlg.comboBox_3.currentIndex == 0:
    item = QCustomTableWidgetItem(str(round((sum(values['%s'])/len(values['%s'])),2)))
else:
    item = QCustomTableWidgetItem(str(round(sum(values['%s'],2))))

for row in range(len(groups)):
    group = QTableWidgetItem(str(groups[row]))
    qTable.setItem(row,0,group)            
    qTable.setItem(row,1,item % row)
</code></pre>

<p>This is the actual code. Not the <code>'%s'</code> and '% row'. I used simplified before not to distract from the actual problem, but I think it's needed. I'm sorry if it wasn't a good decision.</p>

<p>You have a reasonably large misconception about how list slicing works. It will always happen at the time you call it, so inside your if loop itself Python will be trying to slice either of the lists by the literal string <code>"%s"</code>, which can't possibly work.</p>

<p>There is no need to do this. You can just assign <em>the list</em> as the output from the if statement, and then slice that directly:</p>

<pre><code>if condition:
    list_to_slice = my_list
else:
    list_to_slice = my_other_list

# now I do something with this value:
print list_to_slice[3]
</code></pre>

python list