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

Compare and replace lists in function of their lenghts

I have Two lists, let’s say A & B :
(A is the reference name and B is the new name)

What I want is :
if A is bigger than B (len(A)=5 ; len(B) = 3) :the 3 elements B replace the 3 (=>len(B)) firsts elements of A (and print a warning message)

if B is bigger than A (len(A)=5 ; len(B) = 6) : the 5 firsts elements of B replace the 5 (=>len(A)) firsts elements of A (and print a different warning message)

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

if A= B then B replace A

I have a solution but I want to know if it is the fastest or the smartest way of doing it and if some functions do this kind of replacement automatically ?

A = ["A","B","C","D","E"]
B = [1,2,3,4,5,6]

if len(A)>len(B) :
    A[:len(B)] = B
    print("warning message")
if len(B)>len(A) : 
    A[:len(A)] = B[:len(A)]
    print("different warning message")

if len(A) == len(B) :
    A=B

Edit: correction of errors

>Solution :

Why don’t you do a slicing based on the minimum length of the two lists:

A[:min(len(A),len(B))] = B[:min(len(A),len(B))]

A=[1,2,3,4] and B=['a','b','c'] => A = ['a', 'b', 'c', 4]

A=[1,2,3,4] and B=['a','b','c','d','e','f'] => A = ['a', 'b', 'c', 'd']

A=[1,2,3,4] and B=['a','b','c','d'] => A = ['a', 'b', 'c', 'd']

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