Lukeyy
Lukeyy

Reputation: 77

'ValueError: need more than 1 value to unpack' when creating a grid?

I have been tring to make a more difficult grid with 16 words. I have made a grid with 9 words but am unable to do 16 words. I keep on getting the 'ValueError: need more than 1 value to unpack' in my code?

#(Hard) This is the part of the program which puts the words in a Grid.
with open('WordsExt.txt') as f:
    wordshard = random.sample([x.rstrip() for x in f],16)
    gridhard = [wordshard[i:i + 3] for i in range(0, len(wordshard), 3)]
    for x,y,z  in gridhard:
        print (x,y,z)

Upvotes: 0

Views: 64

Answers (2)

PM 2Ring
PM 2Ring

Reputation: 55469

You're doing a 4x4 grid, so those 3s need to become 4s.

Also, you could use the .join method to build each row of your word grid, which makes the output format a little more flexible:

wordshard = [c*4 for c in 'ABCDEFGHIJKLMNOP']
gridhard = [wordshard[i:i + 4] for i in range(0, len(wordshard), 4)]
for row in gridhard:
    print(' '.join(row))

output

AAAA BBBB CCCC DDDD
EEEE FFFF GGGG HHHH
IIII JJJJ KKKK LLLL
MMMM NNNN OOOO PPPP

If we change the last line to print(' | '.join(row)) the output becomes:

AAAA | BBBB | CCCC | DDDD
EEEE | FFFF | GGGG | HHHH
IIII | JJJJ | KKKK | LLLL
MMMM | NNNN | OOOO | PPPP

Alternatively, we can get the same output by using the * "splat" unpacking operator, and specifying a separator string in the print call:

print(*row, sep=' | ')

Upvotes: 0

corinna
corinna

Reputation: 649

Obviously, the error occurs because gridhard does contain less than 3 elements.

The last value of iterator i in the third line of your code example is 15, but wordshard is not longer than 16. In that case, gridhard will only contain 1 letter, and hence, can not be unpacked into three values.

Upvotes: 1

Related Questions