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 ?
Use the extend method
B.extend(['X'] * (len(A)-len(B)))
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']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With