Python:Update list of tuples
<p>I have a list of tuples like this:</p>

<p>list =   [(1, 'q'), (2, 'w'), (3, 'e'), (4, 'r')]</p>

<p>and i am trying to create a update function update(item,num) which search the item in the list and then change the num.</p>

<p>for example if i use update(w,6) the result would be </p>

<pre><code>list =   [(1, 'q'), (6, 'w'), (3, 'e'), (4, 'r')]
</code></pre>

<p>i tried this code but i had error</p>

<pre><code>if item in heap:
        heap.remove(item)
        Pushheap(item,num)
    else:
        Pushheap(item,num)
</code></pre>

<p>Pushheap is a function that push tuples in the heap
any ideas?</p>

<p>As noted in the comments, you are using an immutable data structure for data items that you are attempting to change. Without further context, it looks like you want a dictionary, not a list of tuples, and it also looks like you want the second item in the tuple (the letter) to be the key, since you are planning on modifying the number. </p>

<p>Using these assumptions, I recommend converting the list of tuples to a dictionary and then using normal dictionary assignment. This also assumes that <em>order</em> is not important (if it is, you can use an <code>OrderedDict</code>) and that the same letter does not appear twice (if it does, only the last number will be in the dict).</p>

<pre><code>&gt;&gt;&gt; lst =  [(1, 'q'), (2, 'w'), (3, 'e'), (4, 'r')]
&gt;&gt;&gt; item_dict = dict(i[::-1] for i in lst)
&gt;&gt;&gt; item_dict
{'q': 1, 'r': 4, 'e': 3, 'w': 2}
&gt;&gt;&gt; item_dict['w'] = 6
&gt;&gt;&gt; item_dict
{'q': 1, 'r': 4, 'e': 3, 'w': 6}
</code></pre>

python python-2.7 python-3.x