George Nikolaou George Nikolaou - 1 year ago 173
Python Question

Python:Update list of tuples

I have a list of tuples like this:

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

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

for example if i use update(w,6) the result would be

list = [(1, 'q'), (6, 'w'), (3, 'e'), (4, 'r')]

i tried this code but i had error

if item in heap:

Pushheap is a function that push tuples in the heap
any ideas?

Answer Source

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,

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

update('w', 6)


[(1, 'q'), (6, 'w'), (3, 'e'), (4, 'r')]

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download