3

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']
rzaratx
  • 756
  • 3
  • 9
  • 29

2 Answers2

4

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']
developer_hatch
  • 15,898
  • 3
  • 42
  • 75
2

Just split your list with a proper stepping:

sample1 = ['d', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o']
row1, row2, row3 = [sample1[i:i+4] for i in range(0, len(sample1), 4)]
print(row1, row2, row3)
# ['d', 'e', 'f', 'g'] ['h', 'i', 'j', 'k'] ['l', 'm', 'n', 'o']
RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105