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

391 Views Asked by At

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!

3

There are 3 best solutions below

0
Samwise On BEST ANSWER
>>> mega_list = [["#","#"],["#","#","#"]]
>>> for a in mega_list:
...     a.extend([" "] * (max(map(len, mega_list)) - len(a)))
...
>>> mega_list
[['#', '#', ' '], ['#', '#', '#']]
0
Bobby Ocean On

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)
0
Christian Sloper On

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 ]