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>A list is made up of multiple data values that are referenced by an indice.
So if i defined my list like so :</p>

<pre><code>my_list = [apples, orange, peaches]
</code></pre>

<p>If I want to reference something in the list I do it like this</p>

<pre><code>print(my_list[0]) 
</code></pre>

<p>The expected output for this line of code would be "apples".
To actually add something new to a list you need to use an inbuilt method of the list object, which looks something like this :</p>

<pre><code>my_list.append("foo")
</code></pre>

<p>The new list would then look like this </p>

<pre><code>[apples, orange, peaches, foo]
</code></pre>

<p>I hope this helps.</p>

python list