Skip to content
Advertisement

Truncate sublists to the lowest length

I have:

l = [[1,2,3],[3,4],[1,6,8,3]]

I want:

[[1,2],[3,4],[1,6]]

Which is the list l with all sublists truncated to the lowest length found for the sublists in l.

I tried:

min = 1000

for x in l:
    if len(x) < min: min = len(x)

r = []

for x in l:
    s = []
    for i in range(min):
        s.append(x[i])
    r.append(s.copy())

Which works but quite slow and long to write. I’d like to make this more efficient through list comprehension or similar.

Advertisement

Answer

With list comprehension, one-liner:

l = [[1,2,3],[3,4],[1,6,8,3]]

print ([[s[i] for i in range(min([len(x) for x in l]))] for s in l])

Or:

print ([s[:min([len(s) for s in l])] for s in l])

Output:

[[1, 2], [3, 4], [1, 6]]

We compute the minimal length of subslists in the ‘range()’ to iterate over sublists for that amount and to reconstruct a new subslist. The top-level list comprehension allows to reconstruct the nested sublist.

If you have a large nested list, you should use this version with two lines:

m = min([len(x) for x in l])

print ([[s[i] for i in range(m)] for s in l])

Or:

print ([s[:m] for s in l])

Using zip and preserving the list objects:

print (list([list(x) for x in zip(*zip(*l))]))

Output:

[[1, 2], [3, 4], [1, 6]]
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement