Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: What is the right way to modify list elements?

I've this list with tuples:

l = [('a','b'),('c','d'),('e','f')]

And two parameters: a key value, and a new value to modify. For example,

key = 'a'
new_value= 'B' # it means, modify with 'B' the value in tuples where there's an 'a'

I've this two options (both works):

f = lambda t,k,v: t[0] == k and (k,v) or t 
new_list = [f(t,key,new_value) for t in l]
print new_list 

and

new_list = []
for i in range(len(l)):
    elem = l.pop()
    if elem[0] == key:
        new_list.append((key,new_value))
    else:
        new_list.append(elem)
print new_list

But, i'm new in Python, and don't know if its right.

Can you help me? Thank you!

like image 342
santiagobasulto Avatar asked Aug 01 '26 14:08

santiagobasulto


2 Answers

Here is one solution involving altering the items in-place.

def replace(list_, key, new_value):
    for i, (current_key, current_value) in enumerate(list_):
        if current_key == key:
            list_[i] = (key, new_value)

Or, to append if it's not in there,

def replace_or_append(list_, key, new_value):
    for i, (current_key, current_value) in enumerate(list_):
        if current_key == key:
            list_[i] = (key, new_value)
            break
    else:
        list_.append((key, new_value))

Usage:

>>> my_list = [('a', 'b'), ('c', 'd')]
>>> replace(my_list, 'a', 'B')
>>> my_list
[('a', 'B'), ('c', 'd')]

If you want to create a new list, a list comprehension is easiest.

>>> my_list = [('a', 'b'), ('c', 'd')]
>>> find_key = 'a'
>>> new_value = 'B'
>>> new_list = [(key, new_value if key == find_key else value) for key, value in my_list]
>>> new_list
[('a', 'B'), ('c', 'd')]

And if you wanted it to append if it wasn't there,

>>> if len(new_list) == len(my_list):
...     new_list.append((find_key, new_value))

(Note also I've changed your variable name from l; l is too easily confused with I and 1 and is best avoided. Thus saith PEP8 and I agree with it.)

like image 158
Chris Morgan Avatar answered Aug 04 '26 05:08

Chris Morgan


To create a new list, a list comprehension would do:

In [102]: [(key,'B' if key=='a' else val) for key,val in l]
Out[102]: [('a', 'B'), ('c', 'd'), ('e', 'f')]

To modify the list in place:

l = [('a','b'),('c','d'),('e','f')]

for i,elt in enumerate(l):
    key,val=elt
    if key=='a':
        l[i]=(key,'B')
print(l)              
# [('a', 'B'), ('c', 'd'), ('e', 'f')]
like image 35
unutbu Avatar answered Aug 04 '26 04:08

unutbu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!