Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding and creating chunks of a list in python

Tags:

python

This is my list

list1 = [1,2,3,4,5,6,7,8,9,10,11,12]

i tried to do this

it = iter(list1)

chunked_lists =  zip(it,it,it)

chunked_lists is now = [(1,2,3),(4,5,6),(7,8,9),(10,11,12)]

Now i'd like to add a 'data' to every chunk so that it would look like

[(1,2,3,'data'),(4,5,6,'data')....etc]

but tuples are immutable and i'd have to destroy them, append and create them again.

is there a better way to accomplish this in python?

like image 487
wolfgang Avatar asked Apr 08 '26 08:04

wolfgang


1 Answers

it = iter(list1)
from itertools import repeat
chunked_lists =  zip(it,it,it,repeat("data"))
[(1, 2, 3, 'data'), (4, 5, 6, 'data'), (7, 8, 9, 'data'), (10, 11, 12, 'data')]
like image 138
Padraic Cunningham Avatar answered Apr 10 '26 00:04

Padraic Cunningham



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!