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>You can simply scan through the list looking for a tuple with the desired letter and replace the whole tuple (you can't modify tuples), breaking out of the loop when you've found the required item. Eg,</p>

<pre><code>lst = [(1, 'q'), (2, 'w'), (3, 'e'), (4, 'r')]

def update(item, num):
    for i, t in enumerate(lst):
        if t[1] == item:
            lst[i] = num, item
            break

update('w', 6)
print(lst)
</code></pre>

<p><strong>output</strong></p>

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

<p>However, you should seriously consider using a dictionary instead of a list of tuples. Searching a dictionary is much more efficient than doing a linear scan over a list.</p>

python python-2.7 python-3.x