Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I pass parts of a list to different variables? [duplicate]

Is it possible to pass parts of a list to multiple variables to create new lists? I have a list with 12 words and I want to take the first 4 words and place them in a new list and so on until I have all the words new lists containing 4 words each.

sample1 = ['d', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o']
print(sample1)
row1, row2, row3 = sample1
print(row1)
print(row2)
print(row3)

I get the error:

ValueError: too many values to unpack (expected 3)

My desired final result would be:

row1 = ['d', 'e', 'f', 'g']
row2 = ['h', 'i', 'j', 'k']
row3 = ['l', 'm', 'n', 'o']
like image 856
rzaratx Avatar asked Jan 29 '26 19:01

rzaratx


1 Answers

Of course you can:

sample1 = ['d', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o']

row1, row2, row3 = sample1[0:4], sample1[4:8], sample1[8:12]

print(row1, row2, row3)

result:

['d', 'e', 'f', 'g'] ['h', 'i', 'j', 'k'] ['l', 'm', 'n', 'o']
like image 113
A Monad is a Monoid Avatar answered Jan 31 '26 11:01

A Monad is a Monoid



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!