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>Tuples are an immutable object. Which means once they're created, you can't go changing there contents.</p>

<p>You can, work around this however, by replaceing the tuple you want to change. Possibly something such as this:</p>

<pre><code>def change_item_in_list(lst, item, num):
    for pos, tup in enumerate(lst):
        if tup[1] == item:
            lst[pos] = (num, item)
            return

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

<p>But as @brianpck has already said, you probably want a (ordered)-dictionary instead of a list of tuples.</p>

python python-2.7 python-3.x