Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making equal size lists in Python

I have 3 different lists of unequal length.

I want to append the shorter lists with "X" and make sizes equal to the length of the longest list.

A = [10,20,30,40,50]
B = ["A", "B", "C"]
C = ["X1", "X2"]

After appending "X" , it should be like the following:

A = [10,20,30,40,50]
B = ["A", "B", "C", "X","X"]
C = ["P1", "P2", "X", "X", "X"]

I have used the below code for achieving it,

for i, a in enumerate(A):
    if i < len(B):
        pass
    else:
        B.append('X')

How can i do it efficiently in python ?

like image 221
Biranchi Avatar asked Jun 07 '26 02:06

Biranchi


2 Answers

Use the extend method

B.extend(['X'] * (len(A)-len(B)))
like image 116
jL4 Avatar answered Jun 08 '26 14:06

jL4


Calculate the max length and for each list, append the delta.

In Python, List has a binary operator + to concat multiple lists together, as well as * to tile itself.

A = [10,20,30,40,50]
B = ["A", "B", "C"]
C = ["X1", "X2"]
max_length = max(max(len(A), len(B)), len(C))
A += ['X'] * (max_length - len(A))
B += ['X'] * (max_length - len(B))
C += ['X'] * (max_length - len(C))

Then organize them using a container list, for less repeated codes and better extensibility.

A = [10,20,30,40,50]
B = ["A", "B", "C"]
C = ["X1", "X2"]

arrays = [A, B, C]
max_length = 0
for array in arrays:
    max_length = max(max_length, len(array))

for array in arrays:
    array += ['X'] * (max_length - len(array))

Result:

print(A) # [10, 20, 30, 40, 50]
print(B) # ['A', 'B', 'C', 'X', 'X']
print(C) # ['X1', 'X2', 'X', 'X', 'X']
like image 22
xhg Avatar answered Jun 08 '26 14:06

xhg