Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

padding while creating sublists

Tags:

python

list

Is there an elegant way how to pad the last sublist with zeroes while creating sublists from a list of integers?

So far I have this oneliner and need to fill the last sublist with 2 zeroes

[lst[x:x+3] for x in range(0, len(lst), 3)]

for example

lst =[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

result should be:

[1,2,3][4,5,6][7,8,9][10,0,0]
like image 914
krenkz Avatar asked Jan 22 '26 22:01

krenkz


1 Answers

With itertools.zip_longest, consuming the same iterator created off of the list, and fill in the missing values as 0 :

[[*i] for i in itertools.zip_longest(*[iter(lst)] * 3, fillvalue=0)]

Example:

In [1219]: lst =[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]                                                                                                                                                            

In [1220]: [[*i] for i in itertools.zip_longest(*[iter(lst)] * 3, fillvalue=0)]                                                                                                                             
Out[1220]: [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 0, 0]]
like image 134
heemayl Avatar answered Jan 25 '26 11:01

heemayl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!