TheGIzzardWizzard
TheGIzzardWizzard

Reputation: 21

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]

Upvotes: 0

Views: 1492

Answers (3)

Wups
Wups

Reputation: 2569

Cut any amount of lists to equal lengths:

def even_length(*args):
    target_size = min(map(len, args))
    return tuple(l[:target_size] for l in args)

Usage:

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

a, b = even_length(a, b)
print(a, b)

Of course, you can also pass a list or tuple of lists, if working with individual lists is getting inconvenient.

lists = (a, b, c, d)
lists = even_length(*lists)

Upvotes: 1

Roberto Caboni
Roberto Caboni

Reputation: 7490

Just get the list slice from index 0 to len(a)-1:

b = b[:len(a)]

Output:

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

In case a is bigger than b:

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

Please note how there's no error in case the ending index of the slice is greater than the size of the list.

So, if you don't know what is the shorter array, just perform the slice on both of them:

b = b[:len(a)]
a = a[:len(b)]

and only the bigger one will be "shortened".

Upvotes: 3

Óscar López
Óscar López

Reputation: 236124

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]

Upvotes: 9

Related Questions