Search code examples
pythonarrayscomparison

Match length of arrays in Python


There are some examples online how to subtract values from longer arrays so it matches the length of a shorter one (example). However, the order of values in longer array changes. Is there a way to subtract values from the end of longer array?

This is what I'm trying to achieve:

a = [1, 2, 3, 4, 5]
b = [1, 5, 8, 2, 7, 3, 5, 9, 4, 10]

some code

Output:

a = [1, 2, 3, 4, 5]
b = [1, 5, 8, 2, 7]

Solution

  • This should work, no matter the size or order of the arrays:

    a = [1, 2, 3, 4, 5]
    b = [1, 5, 8, 2, 7, 3, 5, 9, 4, 10]
    
    m = min(len(a), len(b))
    a = a[:m]
    b = b[:m]