Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Expression that returns mutated list

I’m looking for a single expression, mutates an element and returns the modified list

The following is a bit verbose

# key=0; value=3; rng=[1,2]
[(v if i != key else value) for i, v in enumerate(rng)]

Edit:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I’m looking for a way to inline the following function in a single expression

def replace(rng: List, key: int, value):
    a = list(rng) 
    a[key] = value
    return a

>Solution :

Try list concatenation:

key = 0
value = 3
rng = [1, 2]

out = rng[:key] + [value] + rng[key+1:]
print(out)

rng[:key] is a copy of the list up to the key (exclusive), [value] is a new list where the only element is value, and rng[key+1] is a copy of the list from the key on (exclusive). Concatenate these together, and you get a copy where the key is replaced.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading