Python function to update a var in a list of tuple

As part of my new ssh-fail script, now written in python I found myself needing to update a var in a list of a list, but you can’t just do list_a[3][3]= ‘new thing’ :(

so i wrote this function:

def tuple_update(touple, varloc, newval):
    temp = []
    for a in range(len(tuple)):
        if varloc != a:
            temp.append(tuple[a])
        else:
            temp.append(newval)
    return temp

and you can use it like this:

>>>ip_test=[('8.8.8.8', 423, None, 0), ('4.2.2.2', 64, None, 3), ('42.42.42.42', 23, None, 10)]
 
>>> ip_test[1]
('4.2.2.2', 64, None, 3)
>>> ip_test[1]=tuple_update(ip_test[1],1,38)
>>> ip_test[1]
['4.2.2.2', 38, None, 3]
>>> ip_test[2]=tuple_update(ip_test[2],0,'100.100.2.3')
>>> ip_test[2]
['100.100.2.3', 23, None, 10]
>>> ip_test
[['9.9.9.9', 423, None, 0], ['4.2.2.2', 38, None, 3], ['100.100.2.3', 23, None, 10]]

that’s: tuple_update(list,location,newval)

  1. This is list of tuples not list of lists. The ip_test[1][1] = 38 will work fine on list of lists :wink: You can’t change tuple after it’s creation because it’s immutable.


    >>> ip_test=[['8.8.8.8', 423, None, 0], ['4.2.2.2', 64, None, 3], ['42.42.42.42', 23, None, 10]]
    >>> print ip_test
    [['8.8.8.8', 423, None, 0], ['4.2.2.2', 64, None, 3], ['42.42.42.42', 23, None, 10]]
    >>> ip_test[1][1] = 38
    >>> print ip_test
    [['8.8.8.8', 423, None, 0], ['4.2.2.2', 38, None, 3], ['42.42.42.42', 23, None, 10]]

Leave a Comment


NOTE - You can use these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>