Emerald
Emerald

Reputation: 13

Equalizing the lengths of all the lists within a list? (Python)

Important context: Dig on the esolang wiki

I am making an compiler for a esoteric programming language, using a 2d list to account for the language’s 2d nature. The problem comes when I need all the lists in the one mega list to be of same length.

This: [[“#”,”#”],[“#”,”#”,”#”]]

Needs be this: [[“#”,”#”,” “],[“#”,”#”,”#”]]

Thanks!

Upvotes: 0

Views: 431

Answers (3)

Samwise
Samwise

Reputation: 71454

>>> mega_list = [["#","#"],["#","#","#"]]
>>> for a in mega_list:
...     a.extend([" "] * (max(map(len, mega_list)) - len(a)))
...
>>> mega_list
[['#', '#', ' '], ['#', '#', '#']]

Upvotes: 1

Christian Sloper
Christian Sloper

Reputation: 7510

You can do it like this, finding the max length of the lists first:

max_length = max( len(i) for i in l)
[ i + [" "]*(max_length-len(i)) for i in l ]

Upvotes: 0

Bobby Ocean
Bobby Ocean

Reputation: 3294

To apply fillvalues to uneven lists, use the itertools.zip_longest function.

import itertools as it

lists = [[1,2,3],[4,5]]
lists = list(zip(*it.zip_longest(*lists,fillvalue=' ')))
print(lists)

Upvotes: 1

Related Questions